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
递归解法:
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSym(root.left,root.right);
}
public boolean isSym(TreeNode left,TreeNode right){
if(left == null && right == null)
return true;
if(left == null || right == null)
return false;
return left.val == right.val && isSym(left.left,right.right) && isSym(left.right,right.left);
}
}
迭代解法:
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
Stack<TreeNode> leftStack = new Stack<TreeNode>();
Stack<TreeNode> rightStack = new Stack<TreeNode>();
leftStack.push(root.left);
rightStack.push(root.right);
while(leftStack.size() > 0 && rightStack.size() > 0){
TreeNode left = leftStack.pop();
TreeNode right = rightStack.pop();
if(left == null && right == null)
continue;
if(left == null || right == null)
return false;
if(left.val == right.val){
leftStack.push(left.right);
leftStack.push(left.left);
rightStack.push(right.left);
rightStack.push(right.right);
}
else
return false;
}
return true;
}
Note
递归的效率(1ms)要比迭代高,而迭代的话,左子树遍历先序,右子树遍历后序的效率(4ms)又要略低于左子树遍历后序,右子树遍历先序的效率(3ms),不知道迭代的这个变化这个是不是跟后台数据有关。