题目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 [1,2,2,3,4,4,3] is symmetric:
1
/
2 2
/ \ /
3 4 4 3
But the following [1,2,2,null,3,null,3] 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) {
if(root == null){
return true;
}
return dfs(root.left,root.right);
}
private boolean dfs(TreeNode left, TreeNode right){
if(left == null && right == null){
return true;
}
if(left == null || right == null){
return false;
}
if(left.val == right.val){
return dfs(left.left,right.right) && dfs(left.right,right.left);
}else{
return false;
}
}
2,利用"中序"遍历
思路:两次"中序"遍历, 左-根-右, 右-根-左
二者遍历的结果一样,则返回true,否则false
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
StringBuffer forwardSb = new StringBuffer();
StringBuffer reverseSb = new StringBuffer();
Stack<TreeNode> forwardStack = new Stack<TreeNode>();
Stack<TreeNode> reverseStack = new Stack<TreeNode>();
TreeNode forwardNode = root;
TreeNode reverseNode = root;
do{
while(forwardNode != null){
forwardStack.push(forwardNode);
forwardNode = forwardNode.left;
}
while(reverseNode != null){
reverseStack.push(reverseNode);
reverseNode = reverseNode.right;
}
if(forwardStack.size() != reverseStack.size()){
return false;
}
if (!forwardStack.empty()){
forwardNode = forwardStack.pop();
reverseNode = reverseStack.pop();
if(forwardNode.val != reverseNode.val){
return false;
}
forwardNode = forwardNode.right;
reverseNode = reverseNode.left;
}
}while((!forwardStack.empty() || forwardNode != null) && (!reverseStack.empty() || reverseNode != null));
return forwardStack.empty() && reverseStack.empty();
}