子树-LintCode
来源:互联网 发布:企业网络分层设计原则 编辑:程序博客网 时间:2024/06/16 08:02
有两个不同大小的二叉树: T1 有上百万的节点; T2 有好几百的节点。请设计一种算法,判定 T2 是否为 T1的子树。
注意事项:
若 T1 中存在从节点 n 开始的子树与 T2 相同,我们称 T2 是 T1 的子树。也就是说,如果在 T1 节点 n 处将树砍断,砍断的部分将与 T2 完全相同。
样例
下面的例子中 T2 是 T1 的子树:
T1 T2 1 3 / \ / 2 3 4 / 4
下面的例子中 T2 不是 T1 的子树:
T1 T2 1 3 / \ \ 2 3 4 / 4
思路:
当T2为空,必为子树。
当前节点的值相等时,有可能找到相等的子树。假若可以找到,就把此结点与T2结点进行比对(递归),假若找不到,则提前保存T2节点,再将左右子树与T2进行比对。
当前节点的值不相等,将左右子树与T2进行比对。
#ifndef C245_H#define C245_H#include<iostream>using namespace std;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) { // write your code here if (T2 == NULL) return true; return isSubRecur(T1, T2); } bool isSubRecur(TreeNode *T1, TreeNode *T2) { if (T1 == NULL&&T2 == NULL) return true; else if (T2 != NULL&&T1 != NULL) { if (T1->val == T2->val) { return (isSubRecur(T1->left, T2->left) && isSubRecur(T1->right, T2->right)) || (isSubRecur(T1->left, T2) || isSubRecur(T1->right, T2)); } else { return isSubRecur(T1->left, T2) || isSubRecur(T1->right, T2); } } else return false; }};#endif
阅读全文
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子树
- Android学习笔记4---配置文件
- js上传文件获取文件流
- POJ-2186 Popular Cows (SCC 强连通分量)
- Web请求过程
- unity android项目如何快速接入平台支付的SDK
- 子树-LintCode
- c-learning-note(2017-9-20)
- RESET MASTER和RESET SLAVE使用场景和说明,以及清除主从同步关系
- Swift 4.0 正式发布,更快更兼容更好用
- Ora-08103
- 判断单链表是否带环?若带环,求环的长度?求环的入口点?
- IoC源码-获取Document实例
- Android之第三方平台实现QQ登录和QQ分享
- ajax向后台传数组