判断二叉树是否是另一棵二叉树的子树
方法一:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isSubtree(TreeNode s, TreeNode t) {
//思路:将两棵树序列化成一个String类型,判断s1是否包含s2即可
//序列化规则:空子树用#代替,结点分隔符用!
String s1 = preOrder(s);
String s2 = preOrder(t);
if(s1.contains(s2)){
return true;
}else{
return false;
}
}
//迭代:先序遍历
public String preOrder(TreeNode tr){
//注意一开始也要有结点分隔符,不然[12]和[2]这两棵树会被判断为true
StringBuilder sb = new StringBuilder("!");
Stack<TreeNode> stack = new Stack();
TreeNode t = tr;
while(true){
while(t != null){
sb.append(String.valueOf(t.val));
sb.append("!"); //结点分隔符用!
stack.push(t);
t = t.left;
}
sb.append("#!"); //空子树用#,结点分隔符用!
if(!stack.isEmpty()){
TreeNode top = stack.pop();
t = top.right;
}else{
break;
}
}
return sb.toString();
}
}
方法二:
思路
遍历整个s树,看以s树的每个结点为根结点的子树是不是与目标子树t一致,若有一致的,返回true,否则返回false
方法二解法1,层次遍历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 isSubtree(TreeNode s, TreeNode t) {
//层次遍历s,依次比较【以s中的结点为根结点的子树】与t是否相等
Queue<TreeNode> q = new LinkedList();
q.offer(s);
while(!q.isEmpty()){
TreeNode ts = q.poll();
boolean res = sameTree(ts,t);
if(res == true){
return true;
}
if(ts.left != null){
q.offer(ts.left);
}
if(ts.right != null){
q.offer(ts.right);
}
}
return false;
}
public boolean sameTree(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 sameTree(s.left, t.left) && sameTree(s.right, t.right);
}
}
方法二解法2,递归调用:
c++实现:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (!s) return false;
if (sameTree(s, t)) return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool sameTree(TreeNode* s, TreeNode* t) {
if (!s && !t) return true;
if (!s || !t) return false;
if (s->val != t->val) return false;
return sameTree(s->left, t->left) && sameTree(s->right, t->right);
}