码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 572. 另一个树的子树

时间:2019-08-17 10:55:40      阅读:95      评论:0      收藏:0      [点我收藏+]

标签:包含   tps   style   返回   bool   str   节点   pre   The   

题目链接:https://leetcode-cn.com/problems/subtree-of-another-tree/

给定两个非空二叉树 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。

思路:

一个树是另一个树的子树 则

  • 要么这两个树相等
  • 要么这个树是左树的子树
  • 要么这个树hi右树的子树
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     struct TreeNode *left;
 6  *     struct TreeNode *right;
 7  * };
 8  */
 9 bool isSame(struct TreeNode* s, struct TreeNode* t)
10 {
11     if(s!=NULL&&t==NULL) return false;
12     if(t!=NULL&&s==NULL) return false;
13     if(s==NULL&&t==NULL) return true;
14     if(s->val!=t->val) return false;
15     return isSame(s->left,t->left)&&isSame(s->right,t->right);
16 }
17 bool isSubtree(struct TreeNode* s, struct TreeNode* t){
18     if(s==NULL) return false;
19     if(isSame(s,t)) return true;
20     return isSubtree(s->left,t)||isSubtree(s->right,t);
21 }

 

LeetCode 572. 另一个树的子树

标签:包含   tps   style   返回   bool   str   节点   pre   The   

原文地址:https://www.cnblogs.com/shixinzei/p/11367414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!