s为大树,t为小树
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
题目网址:https://leetcode-cn.com/problems/subtree-of-another-tree/
思路:
- 两个树都是空树,返回true
- 如果两个树一个是空,一个不是空,不包含
- 两个树都是非空
a)比较根节点的值是不是相等,如果相等的话,比较一下s和t是不是相同的树
b)递归的判定一下,t是否被s的左子树包含
c)递归的判定一下,t是否被s的右子树包含。
具体代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
//判断是否相等的方法
public boolean isSametree(TreeNode s, TreeNode t){
if(s == null && t == null){
return true;
}
if(s == null || t == null){
return false;
}
if(s.val != t.val){
return false;
}
return isSametree(s.left,t.left) && isSametree(s.right,t.right);
}
public boolean isSubtree(TreeNode s, TreeNode t) {
if(s == null && t == null){
return true;
}
if(s == null || t == null){
return false;
}
boolean ret = false;
if(s.val == t.val){
ret = isSametree(s,t);
}
if(!ret){
ret = isSubtree(s.left,t);
}
if(!ret){
ret = isSubtree(s.right,t);
}
return ret;
}
}
这一题的重要思路是,用isSametree来大事化小
首先递归遍历大的s树,看能不能找到节点和t根节点相同的点,如果找到了,用isSametree来保存,返回true即可。
如果没有找到就继续递归遍历,先左子树,再右子树
847



被折叠的 条评论
为什么被折叠?



