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.
中文:给定两颗二叉树,写一个函数判断这两棵树是否相等。如果两棵树的结构和各节点中保存的值是相等的,则认为这两棵树相等。
递归和非递归两种方法
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
//方法一:递归
/*
if (p == null || q == null){
return p == q;
}
if (p.val != q.val){
return false;
}
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
*/
//方法二:非递归
Stack<TreeNode> stack1 = new Stack<>();
Stack<TreeNode> stack2 = new Stack<>();
stack1.push(p);
stack2.push(q);
while(!stack1.isEmpty() && !stack2.isEmpty()){
TreeNode n1 = stack1.pop();
TreeNode n2 = stack2.pop();
if (n1 == null && n2 == null){
continue;
}
if (n1 == null || n2 == null || n1.val != n2.val){
return false;
}
stack1.push(n1.left);
stack2.push(n2.left);
stack1.push(n1.right);
stack2.push(n2.right);
}
return true;
}
}