题目
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
分析
1 两种思路 一种是递归,但是要注意递归的参数是要有两个, 左右结点 ,因此需要再写一个函数
非递归的思路要注意的是 对于树这种结构 要想到用栈来保存结点,然后再弹出,再进行比较,处理起来有奇效
2 判断返回的时候,这两行代码实在是妙的不行
if(left == null || right == null) return left == right;
直接包含了三种情况, 用两行代码实现了
代码
public boolean isSymmetric(TreeNode root) {
if(root == null) return true;
Stack<TreeNode> stack = new Stack<>();
stack.push(root.left);
stack.push(root.right);
while (!stack.empty()){
TreeNode n1 = stack.pop(), n2 = stack.pop();
if(n1 == null && n2 == null) continue;
if(n1 == null || n2 == null || n1.val != n2.val) return false;
stack.push(n1.left);
stack.push(n2.right);
stack.push(n1.right);
stack.push(n2.left);
}
return true;
// return root == null || isSymmetricHelp(root.left, root.right);
}
public boolean isSymmetricHelp(TreeNode left, TreeNode right){
if(left == null || right == null) return left == right;
if(left.val != right.val) return false;
return isSymmetricHelp(left.left, right.right) && isSymmetricHelp(left.right, right.left);
}