Given two binary trees, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical and the nodes have the same value.
Example 1:
Input: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
Output: true
Example 2:
Input: 1 1
/ \
2 2
[1,2], [1,null,2]
Output: false
Example 3:
Input: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
Output: false
因为第一次接触二叉树的代码,所以直接参考了网上的程序,因为二叉树深度可以很深,所以最简便的方法是递归。
1.判断根节点的数值是否相等,再判断根节点的左节点数值是否相等、右节点数值是否相等。
2.将左节点作为根节点,将右节点作为根节点,重复步骤1.(注意及时跳出)
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p == null && q == null) return true;//两个结点为空则一定相等
else if(p == null || q == null) return false;//如果不是两个空结点,又有其中一个是空的,那一定一空一非空,一定不相等
else if(p.val == q.val)//如果两个结点都不为空,则比较数值是否相等,如果相等再递归左&&右结点
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}