LeetCode:101. 對稱二叉樹 (Java)
阿新 • • 發佈:2019-01-05
題目:
給定一個二叉樹,檢查它是否是映象對稱的。
例如,二叉樹 [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
說明:
如果你可以運用遞迴和迭代兩種方法解決這個問題,會很加分。
解答:
1. 樹是空的,true。
2. 判斷這棵樹的左子樹和右子樹是否對稱。
3. 兩棵子樹的對稱條件:根節點相等,左子樹的左子樹和右子樹的右子樹對稱,左子樹的右子樹和右子樹的左子樹對稱:
2 2
/ \ / \
3 4 4 3
/ \ / \ / \ / \
5 6 7 8 8 7 6 5
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public boolean isSymmetric(TreeNode root) { if (root == null) { return true; } else { return isSymmetric(root.left, root.right); } } private boolean isSymmetric(TreeNode left, TreeNode right) { if (left == null && right == null) { return true; } else if (left == null || right == null) { return false; } return left.val == right.val && isSymmetric(left.left, right.right) && isSymmetric(left.right, right.left); } }