[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);}
阅读全文
0 0
- [LeetCode]572. Subtree of Another Tree
- [leetcode]: 572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- [leetcode: Python]572. Subtree of Another Tree
- [leetcode]572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode] 572. Subtree of Another Tree
- LeetCode-572. Subtree of Another Tree (Java)
- Leetcode-572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- [LeetCode]572. Subtree of Another Tree
- 【LeetCode】572. Subtree of Another Tree
- leetcode 572. Subtree of Another Tree
- leetcode#572. Subtree of Another Tree
- LeetCode 572. Subtree of Another Tree
- LeetCode刷题 | 572. Subtree of Another Tree
- LeetCode: Subtree of Another Tree
- git的一些用法命令
- MYSQL索引优化, IN OR 等优化措施
- 拿到一台新的linux机器要做哪些事情
- 数据结构(2)——大话数据结构
- PhpStorm2016.3激活和汉化
- [leetcode]: 572. Subtree of Another Tree
- Spring整合JMS(一)——基于ActiveMQ实现
- java实现快速排序
- armlinux中一些重要的宏-如unlikely、container_of及地址定义
- Linux安装,简单介绍
- 『ORACLE』root切换oracle报错(11g)
- 看《欢乐颂》五大美女独自在家_用什么智能用具...
- 安装Keras(TensorFlow做后端)
- 多通道卷积计算