LeetCode-Symmetric Tree
阿新 • • 發佈:2018-12-20
Description: 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
題意:判斷一顆二叉樹是否為一顆映象二叉樹
解法:映象二叉樹如圖所示,其左子樹的所有節點翻轉後與右子樹對應節點相同;因此,我們只需要遞迴的計算二叉樹的根節點與其左右兩個子樹的節點,相對應翻轉後是否相同;
Java
/** * 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) { return isMirror(root, root); } private boolean isMirror(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 isMirror(root1.left, root2.right) && isMirror(root1.right, root2.left); } }