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 public boolean isSymmetric(TreeNode root) { 2 if (root == null) return true; 3 return helper(root.left, root.right); 4 } 5 private boolean helper(TreeNode left, TreeNode right) { 6 if (left == null) return right == null; 7 if (right == null) return left == null; 8 if (left.val == right.val) { 9 return helper(left.left, right.right) && helper(left.right, right.left); 10 }else{ 11 return false; 12 } 13 }
1 public boolean isSymmetric(TreeNode root) { 2 if (root == null) { 3 return true; 4 } 5 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 6 queue.offer(root.left); 7 queue.offer(root.right); 8 TreeNode left; 9 TreeNode right; 10 while (!queue.isEmpty()) { 11 left = queue.poll(); 12 right = queue.poll(); 13 if (left == null && right == null) { 14 continue; 15 } 16 if (left == null || right == null || left.val != right.val) { 17 return false; 18 } 19 queue.offer(left.left); 20 queue.offer(right.right); 21 queue.offer(left.right); 22 queue.offer(right.left); 23 } 24 return true; 25 }
原文:http://www.cnblogs.com/gonuts/p/4647423.html