欢迎转载,转载请注明原地址:
http://blog.csdn.net/u013190088/article/details/64444050
Description
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) return false;
if(p.val == q.val)
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}
如果不用递归,用两个栈也可以解决。