LintCode 子树
来源:互联网 发布:数据统计与分析专业 编辑:程序博客网 时间:2024/05/22 15:04
题目描述:
有两个不同大小的二进制树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。
注意事项
若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。
您在真实的面试中是否遇到过这个题? Yes
样例
下面的例子中 T2 是 T1 的子树:
1 3 / \ /
T1 = 2 3 T2 = 4
/
4
下面的例子中 T2 不是 T1 的子树:
1 3 / \ \
T1 = 2 3 T2 = 4
/
4
ac代码:
/** * 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, T2: The roots of binary tree. * @return: True if T2 is a subtree of T1, or false. */ bool dfs(TreeNode* a, TreeNode* b) { if(a==NULL && b==NULL) return 1; if(a!=NULL && b!=NULL && a->val==b->val) { return dfs(a->left,b->left) && dfs(a->right,b->right); } return 0; } bool isSubtree(TreeNode *T1, TreeNode *T2) { // write your code here bool flag=0; if(T2==NULL) return 1; if(T1==NULL) return 0; //if(T1->val==T2->val) flag=dfs(T1,T2); if(!flag) flag=isSubtree(T1->left,T2); if(!flag) flag=isSubtree(T1->right,T2); return flag; }};
0 0
- LintCode 子树
- lintcode-子树
- lintcode ----子树
- lintcode,子树
- LintCode 子树
- 子树-LintCode
- LintCode-子树
- Lintcode 子树
- lintcode子树
- LintCode 子树
- LintCode 子树
- 子树-LintCode
- 子树(LintCode)
- lintcode subtree 子树
- lintcode——子树
- [LintCode]245.子树
- LintCode-剑指Offer-(245)子树
- lintcode-递归-简单-245子树
- IntelliJ Idea 常用快捷键列表
- LintCode 把排序数组转换为高度最小的二叉搜索树
- 用户登录记住密码
- ZUNIONSTORE
- FZU2092-收集水晶
- LintCode 子树
- javascript继承
- Android GPS定位(获取经纬度)
- java多线程:17、面试题1
- python2 与Python 3 的区别(持续更新...)
- Android RadioButton代码去掉圆点绝对有效
- Java代码实现调用BAT脚本文件杀死进程
- 数据结构——JAVA实现静态链表
- day02_JS&DOM