[leetcode]: 572. Subtree of Another Tree

来源:互联网 发布:python subprocess cwd 编辑:程序博客网 时间:2024/06/11 19:34

1.题目

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.

给定2叉树s,t.判断t是否为s的一个子树

2.分析

递归的判断
1)根结点元素值是否相同
如果相同,则判断以该节点为根结点的s的子树是否与t相同
如果不相同,则递归的判断
2)t是否为【s的左子树】的子树
3)t是否为【s的右子树】的子树

3.代码

bool isSubtree(TreeNode* s, TreeNode* t) {    if (s == NULL || t == NULL)        return s == t;    if (s->val == t->val && isSameTree(s, t))//根结点值相同则判断整棵树是否相同        return true;    else//否则就看s的左右子树        return isSubtree(s->left, t) || isSubtree(s->right, t);}bool isSameTree(TreeNode* s, TreeNode* t) {    if (s == NULL || t == NULL)        return s == t;    if (s->val != t->val)//same的条件是每个节点的值都相同        return false;    return isSameTree(s->left, t->left) && isSameTree(s->right, t->right);}