LeetCode OJ 101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
判断一棵树是不是对称的,那么我们需要对比两个位置对称的节点,首先判断这两个节点的值是否相等,然后判断这两个节点的子树是否对称。这就是递归的思路,从根节点的左右子树开始,递归向下。代码如下:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public boolean isSymmetric(TreeNode root) { 12 if(root == null) return true; 13 return isSame(root.left, root.right); 14 } 15 16 public boolean isSame(TreeNode root1, TreeNode root2){ 17 if(root1==null && root2==null) return true; 18 if(root1!=null && root2!=null){ 19 if(root1.val != root2.val) return false; 20 else{ 21 boolean a = isSame(root1.left, root2.right); 22 boolean b = isSame(root1.right, root2.left); 23 if(a==true && b==true) return true; 24 else return false; 25 } 26 } 27 return false; 28 } 29 }