题目:
Given two non-empty binary trees
s
andt
, check whether treet
has exactly the same structure and node values with a subtree ofs
. A subtree ofs
is a tree consists of a node in s and all of this node’s descendants. The trees
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.
Example 2:
Given tree s:3 / \ 4 5 / \ 1 2 / 0
Given tree t:
4 / \ 1 2
Return false.
解释:
判断一棵树是不是另一颗树的子树,注意子树的要求是小树的叶子节点在大树中也是叶子节点,和剑指offer中判断一棵树是不是另一棵树的子结构不一样。比如上面的实例2,树t
是树s
的子结构但是不是它的子树。
判断一棵树是不是另一棵树的子结构(ps:空树不是任意一个树的子结构),python代码:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
#判断树A以r为根节点的子树是不是和树B有相同的结构
def isSub(t1,t2):
if not t2:
return True
elif not t1:
return False
else:
return t1.val==t2.val and isSub(t1.left,t2.left) and isSub(t1.right,t2.right)
if not pRoot1 or not pRoot2:
return False
#在A中查找与根结点一样的结点
return isSub(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
需要用到100. Same Tree(python+cpp),注意上面的isSub()
和isSame()
有一些区别,isSub()
要求只要有部分结构相同就可以但是isSame()
要求整个结构的都要相同。
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def isSame(r1,r2):
if r1 and r2:
return r1.val==r2.val and isSame(r1.left,r2.left) and isSame(r1.right,r2.right)
return r1==r2
if not t:
return True
elif not s:
return False
return isSame(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSubtree(TreeNode* s, TreeNode* t) {
if (!t)
return true;
else if(!s)
return false;
return isSame(s,t) or isSubtree(s->left,t) or isSubtree(s->right,t);
}
bool isSame(TreeNode*r1,TreeNode*r2)
{
if (r1 &&r2)
return r1->val==r2->val && isSame(r1->left,r2->left) &&isSame(r1->right,r2->right);
return r1==r2;
}
};
总结:
还有先把树结构转换成str再比较的,我还是觉得这种解法更经典一点。