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.
递归解法
1 /** 2 * Definition for binary tree 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 // Start typing your Java solution below 13 // DO NOT write main() function 14 if(root == null){ 15 return true; 16 } 17 18 //if(root.left != null && root.right != null){ 19 return cmp(root.left, root.right); 20 //} 21 22 //return false; 23 } 24 25 public boolean cmp(TreeNode l, TreeNode r){ 26 boolean f1 = false, f2 = false; 27 if(l == null && r == null){ 28 return true; 29 } 30 31 if((l != null && r == null) || 32 (l == null && r != null)){ 33 return false; 34 } 35 36 if(l.val != r.val){ 37 return false; 38 } 39 //if(l.left != null && r.right != null){ 40 f1 = cmp(l.left, r.right); 41 //} 42 //if(l.right != null && r.left != null){ 43 f2 = cmp(l.right, r.left); 44 //} 45 //if(l != null && r != null && f1 && f2){ 46 // return false; 47 //} 48 if(f1 && f2){ 49 return true; 50 } 51 return false; 52 53 } 54 }
迭代版本(层序遍历)
1 /** 2 * Definition for binary tree 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 // Start typing your Java solution below 13 // DO NOT write main() function 14 if(root == null){ 15 return true; 16 } 17 LinkedList<TreeNode> l = new LinkedList<TreeNode>(), 18 r = new LinkedList<TreeNode>(); 19 20 l.add(root.left); 21 r.add(root.right); 22 while(!l.isEmpty() && !r.isEmpty()){ 23 TreeNode t1 = l.poll(), t2 = r.poll(); 24 if((t1 == null && t2 != null) || (t1 != null && t2 == null)){ 25 return false; 26 } 27 if(t1 != null){ 28 if(t1.val != t2.val){ 29 return false; 30 } 31 l.add(t1.left); 32 l.add(t1.right); 33 r.add(t2.right); 34 r.add(t2.left); 35 } 36 } 37 return true; 38 } 39 }