Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
该题比较简单,不作解释,不懂的话,欢迎提问~
public class IsSameTree {
//递归实现
public boolean isSameTree(TreeNode p,TreeNode q) {
if(p==null && q==null) return true;
if(p==null || q==null) return false;
return (p.val==q.val) && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
//非递归
public boolean isSameTree2(TreeNode p,TreeNode q) {
Stack<TreeNode> stack = new Stack<>();
stack.push(p);
stack.push(q);
while(!stack.isEmpty()) {
q=stack.pop();
p=stack.pop();
if(p==null && q==null) continue;
if(p==null || q==null) return false;
if(p.val!=q.val) return false;
stack.push(p.left);
stack.push(q.left);
stack.push(p.right);
stack.push(q.right);
}
return true;
}
}