【题目】
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 TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p!=null && q!=null)
return (p.val==q.val) &&(isSameTree(p.left,q.left)) && (isSameTree(p.right,q.right));
else if(p==null && q==null) return true;
else return false;
}