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
题目很简单,一个递归遍历就出来的,但是发现了一种精简代码的形式
我以前的写法
if (p == null && q == null) {
return true;
}
if (p == null || q == null) {
return false;
}
这是判断两个引用是否只有其中一个为空,如果是返回false,如果都为空返回真。其实这些代码可以用一行来表示
if (p == null || q == null) return (p == q);
是不是觉得特别爽了
所以这题的代码只有三行
public boolean isSameTree(TreeNode p, TreeNode q) {
if (p == null || q == null) return (p == q);
if (p.val == q.val) return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
return false;
}