原题再现:
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 boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;
if(p == null || q == null || p.val != q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
深层次来说,一句话也可以将其实现:
public boolean isSameTree(TreeNode p, TreeNode q) {
return (p == null || q == null) ? p == q : p.val == q.val &&
isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}
算法二:
利用栈的思想:
(1)只利用一个栈就可以实现:
public boolean isSameTree(TreeNode p, TreeNode q) {
Stack stack = new Stack();
stack.push(q);
stack.push(p);
while(!stack.isEmpty()){
TreeNode pn = stack.pop();
TreeNode qn = stack.pop();
if(pn == null && qn == null){
continue;
}else if(pn == null || qn == null){
return false;
}else if(pn.val != qn.val){
return false;
}
stack.push(pn.right);
stack.push(qn.right);
stack.push(pn.left);
stack.push(qn.left);
}
return true;
}
(2)利用双栈也可以实现:
public boolean isSameTree(TreeNode p, TreeNode q) {
Stack stack_p = new Stack <> ();
Stack stack_q = new Stack <> ();
if (p != null) stack_p.push( p ) ;
if (q != null) stack_q.push( q ) ;
while (!stack_p.isEmpty() && !stack_q.isEmpty()) {
TreeNode pn = stack_p.pop() ;
TreeNode qn = stack_q.pop() ;
if (pn.val != qn.val) return false ;
if (pn.right != null) stack_p.push(pn.right) ;
if (qn.right != null) stack_q.push(qn.right) ;
if (stack_p.size() != stack_q.size()) return false ;
if (pn.left != null) stack_p.push(pn.left) ;
if (qn.left != null) stack_q.push(qn.left) ;
if (stack_p.size() != stack_q.size()) return false ;
}
return stack_p.size() == stack_q.size() ;
}