[LintCode]245.子树
来源:互联网 发布:军团要塞2画面优化cfg 编辑:程序博客网 时间:2024/05/21 12:08
有两个不同大小的二进制树: T1
有上百万的节点; T2
有好几百的节点。请设计一种算法,判定 T2
是否为 T1
的子树。
注意事项
若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。
下面的例子中 T2 是 T1 的子树:
1 3 / \ / T1 = 2 3 T2 = 4 / 4
下面的例子中 T2 不是 T1 的子树:
1 3 / \ \T1 = 2 3 T2 = 4 / 4
/** * Definition of TreeNode: * class TreeNode { * public: * int val; * TreeNode *left, *right; * TreeNode(int val) { * this->val = val; * this->left = this->right = NULL; * } * } */class Solution {public: /* * @param T1: The roots of binary tree T1. * @param T2: The roots of binary tree T2. * @return: True if T2 is a subtree of T1, or false. */ bool isSubtree(TreeNode * T1, TreeNode * T2) { //这个要加上,否则出现错误,因为下面加了判断条件 if(T1==NULL && T2==NULL){ return true; } if(T1 == NULL ){ return false; } if(T2 == NULL){ return true; } bool result = false; if(T1!=NULL && T2!=NULL){ if(T1->val==T2->val){ result = isEqual(T1,T2); } if(!result){ result = isSubtree(T1->left,T2); } if(!result){ result = isSubtree(T1->right,T2); } } return result; } bool isEqual(TreeNode *T1, TreeNode *T2) { if(T1 == NULL && T2 == NULL){ return true; } //T1!=NULL && T2!=NULL要加上,否则出现错误if(T1!=NULL && T2!=NULL && T1->val == T2->val){ return isEqual(T1->left,T2->left) && isEqual(T1->right,T2->right); } return false; } };
阅读全文
0 0
- [LintCode]245.子树
- LintCode 子树
- lintcode-子树
- lintcode ----子树
- lintcode,子树
- LintCode 子树
- 子树-LintCode
- LintCode-子树
- Lintcode 子树
- lintcode子树
- LintCode 子树
- LintCode 子树
- 子树-LintCode
- 子树(LintCode)
- lintcode subtree 子树
- lintcode——子树
- LintCode-剑指Offer-(245)子树
- lintcode-递归-简单-245子树
- NKOJ 1979 投票
- 小 X的密室
- TensorFlow中常见的由于API版本问题导致的错误汇总
- PAT基础题 4-13 折半查找
- jetson TX2如何安装opencv3.0
- [LintCode]245.子树
- ubuntu配置vps+ss
- LeetCode:38.Count and Say
- CentOS6.5安装elasticsearch-5.5.1以及elasticsearch-sql插件安装
- PE文件学习笔记(一):DOS头与PE头解析
- linux各种中文乱码解决办法整理
- LeetCode
- Java——Comparable和Comparator(二)
- L2-021. 点赞狂魔