leetcode 572. Subtree of Another Tree(判断子树)-爱代码爱编程
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could 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.
给出两棵二叉树s和t, 判断t是不是s的子树。
思路:
用到了相同树的判断,如果不是相同的树,就进一步判断t 在s的左子树,右子树中有没有相同的树
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null) return false;
if(isSame(s, t)) return true;
return isSubtree(s.left, t) || isSubtree(s.right, t);
}
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) return isSame(s.left, t.left) && isSame(s.right, t.right);
return false;
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 本文链接: https://blog.csdn.net/level_code/article/details/111036261