【题目】
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:
给定的树 s:
3
/ \
4 5
/ \
1 2
/
0
给定的树 t:
4
/ \
1 2
返回 false。
【思路】
(昨天才说递归很简单,今天就没做出来。。。大概思路是对的,没调通)
写两个递归函数方便理解点。
第一个递归函数主要找到s中和t根节点值相同的节点;
第二个递归函数主要判断s中某个子树是否和t完全相同。
【代码】
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
"""
if not s and t:
return False
# 树是否相同
if self.is_same(s, t):
return True
# 不同则继续遍历孩子节点
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def is_same(self, s, t):
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
return False
return self.is_same(s.left, t.left) and self.is_same(s.right, t.right)
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(not s and t)
return false;
if(is_same(s, t))
return true;
return isSubtree(s->left, t) || isSubtree(s->right, t);
}
bool is_same(TreeNode* s, TreeNode* t){
if(not s and not t)
return true;
if(not s or not t)
return false;
if(s->val != t->val)
return false;
return is_same(s->left, t->left) && is_same(s->right, t->right);
}
};