LC 101
- 使用递归或者迭代
- 递归:找到可以重复的模式,即为递归函数helper的内容
- 现实中一般不用递归,过深时可能会导致栈溢出
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root==null)return true;
return helper(root.left,root.right);
}
public boolean helper(TreeNode root1,TreeNode root2){
if (root1==null && root2==null) return true;
if (root1==null || root2==null) return false;
if (root1.val !=root2.val) return false;
return helper(root1.left,root2.right) && helper(root1.right,root2.left);
}
import java.util.Stack;
class Solution {
public boolean isSymmetric(TreeNode root) {
if (root==null)return true;
Stack<TreeNode> s=new Stack<TreeNode>();
s.push(root.left);
s.push(root.right);
while(!s.isEmpty()){
TreeNode root1=s.pop();
TreeNode root2=s.pop();
if (root1==null && root2==null)continue;
if (root1==null||root2==null||root1.val!=root2.val)return false;
s.push(root1.left);
s.push(root2.right);
s.push(root1.right);
s.push(root2.left);
}
return true;
}
}
}