/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
return isSymmetricHelper(root.left, root.right);
}
private boolean isSymmetricHelper(TreeNode left, TreeNode right){
if(right == null && left == null)
return true;
if(right == null || left == null)
return false;
return right.val == left.val && isSymmetricHelper(left.left, right.right) && isSymmetricHelper(left.right, right.left);
}
}
迭代版本:
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null)
return true;
Stack<TreeNode> s = new Stack<>();
s.push(root.left);
s.push(root.right);
while(!s.empty()){
TreeNode nd1 = s.pop();
TreeNode nd2 = s.pop();
if(nd1==null && nd2==null)
continue;
if(nd1==null || nd2==null)
return false;
if(nd1.val!=nd2.val)
return false;
s.push(nd1.left); s.push(nd2.right);
s.push(nd1.right); s.push(nd2.left);
}
return true;
}
}
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.