樹 --- Leecode 101 判斷是否是對稱樹 (Easy)

題目

給定一個二叉樹,檢查它是否是鏡像對稱的。

例如,二叉樹 [1,2,2,3,4,4,3] 是對稱的。

    1
   / \
  2   2
 / \ / \
3  4 4  3
但是下面這個 [1,2,2,null,3,null,3] 則不是鏡像對稱的:

    1
   / \
  2   2
   \   \
   3    3

解答

思路: 遞歸。比較兩個節點的左子樹與右子樹,右子樹與左子樹是否相等。

js代碼:

var isSymmetric = function(root) {
      if(root == null) return true;
      return helper(root.left, root.right);

    function helper(root1, root2) {
       if(root1 == null && root2 == null) return true;
       if(root1 == null || root2 == null) return false;
       if(root1.val != root2.val) return false;
       return  helper(root1.left, root2.right) &&  helper(root1.right, root2.left);
    }
};

java代碼:

class Solution {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) return true;
        return helper(root.left, root.right);
    }
    private boolean helper (TreeNode root1, TreeNode root2) {
        if(root1 == null && root2 == null) return true;
        if(root1 == null || root2 == null) return false;
        if(root1.val != root2.val) return false;
        return  helper(root1.left, root2.right) && helper(root1.right, root2.left);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章