一、问题描述
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.
二、问题分析
树的遍历问题。一般情况下只是遍历一棵树,此题无非同时遍历两个树罢了。采用先序遍历,当然也可以采用其它的。
三、Java AC代码
public boolean isSameTree(TreeNode p, TreeNode q) {
return preOrderTravel(p, q);
}
public boolean preOrderTravel(TreeNode p, TreeNode q) {
if (p==null && q==null) {
return true;
}
if (p==null && q!=null) {
return false;
}
if (p!=null && q == null) {
return false;
}
if (p.val == q.val) {
return preOrderTravel(p.left, q.left) && preOrderTravel(p.right, q.right);
}else {
return false;
}
}