对称的二叉树
解法一:递归
按照层级关系,每次比较左子节点和右子节点是否相同,如果不同则为false,直到比较到左右结点均为null时证明比较完成,返回true
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
return bfs(root.left, root.right);
}
public boolean bfs(TreeNode left, TreeNode right){
if(left == null && right == null){
return true;
}
if(left == null || right == null){
return false;
}
if(left.val != right.val){
return false;
}
return bfs(left.left, right.right) && bfs(left.right, right.left);
}
}
解法二:迭代
根据中序遍历的迭代算法,使用栈存储结点路径
中序遍历:左 根 右
反向中序遍历:右 根 左
所以如果一个二叉树是对称二叉树的话那么他的中序遍历和反向中序遍历一定相同
class Solution {
public boolean isSymmetric(TreeNode root) {
if(root == null){
return true;
}
Stack<TreeNode> left = new Stack();
Stack<TreeNode> right = new Stack();
TreeNode l = root.left;
TreeNode r = root.right;
while(l != null || r != null || left.size() != 0 || right.size() != 0){
while(l != null && r != null){
left.push(l);
right.push(r);
l = l.left;
r = r.right;
}
if(l != null || r != null){
return false;
}
l = left.pop();
r = right.pop();
if(l.val != r.val){
return false;
}
l = l.right;
r = r.left;
}
return true;
}
}