題目敘述

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

先附上通關證明

 

對稱樹就是在相對位置應該要長得一樣,要反覆檢查到最尾端,這種不知道要做幾次的事,感覺可用遞回去寫。

對稱樹我的解讀就是相反的相對路徑要長得一樣,譬如說 左 = 右,左 -> 右 = 右 ->左 ,右 -> 右 = 左 ->左。

然後把這個想法練習寫成 Js :

var isSymmetric = function(root) {

    if(root==null)return true;

    return checkTwo(root.left,root.right);
}

var checkTwo = function(a , b){

    if(a==null || b==null){

        return a==null && b ==null;

    }

    if(a.val!=b.val)

    return false;

    return checkTwo(a.left,b.right)&&checkTwo(b.left,a.right);

};

 

我寫兩個=是我覺得這邊null 應該跟undefine差不多意義,就沒有細分。

arrow
arrow
    全站熱搜

    Deyu 發表在 痞客邦 留言(0) 人氣()