Problem
Given two non-empty binary treessandt, check whether treethas exactly the same structure and node values with a subtree ofs. A subtree ofsis a tree consists of a node insand all of this node's descendants. The treescould also be considered as a subtree of itself.
Example 1:
Given tree s:
3
/ \
4 5
/ \
1 2
Given tree t:
4
/ \
1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3
/ \
4 5
/ \
1 2
/
0
Given tree t:
4
/ \
1 2
Return false.
错误思路
- 直接就想用isSubtree来解决全部。 实际上要从逻辑去想问题,而非一脑子地去用某个固化的方式去解决
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null || t == null) return false;
if (s.val == t.val && isSubtree(s.left, t.left) && isSubtree(s.right, t.right)) return true;
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
正确思路
- 在上面的基础上更改
- 如果当前s.val == t.val, 那么他们的左子树相同,右子树也相同
public boolean isSubtree(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null || t == null) return false;
if (s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right)) return true;
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
public boolean isSame(TreeNode s, TreeNode t) {
if (s == null && t == null) return true;
if (s == null || t == null) return false;
if (s.val == t.val && isSame(s.left, t.left) && isSame(s.right, t.right)) return true;
return false;
}