子树/最近公共祖先
来源:互联网 发布:centos 安装lamp环境 编辑:程序博客网 时间:2024/06/08 10:20
判断一颗二叉树是是否是另一颗树的子树
class Solution {public: bool test(TreeNode* T1,TreeNode* T2) { if(T1==NULL && T2==NULL) return true; if(T1==NULL||T2==NULL||T1->val!=T2->val) return false; return test(T1->left,T2->left)&&test(T1->right,T2->right); } bool isSubtree(TreeNode *T1, TreeNode *T2) { // write your code here if( T2==NULL ) return true; if(T1==NULL) return false; if(T1->val==T2->val) { if(test(T1,T2)) return true; } return isSubtree(T1->left,T2)||isSubtree(T1->right,T2); }};
判断一棵树是否是完全二叉树
bool istree(TreeNode* root){ queue<TreeNode*> q; q.push(root); int count = 1; int isbintree = 1; while (!q.empty()) { count = q.size(); while (count--) { Node* tmp = q.front(); q.pop(); cout << tmp->val << endl; if (tmp->left) { if (isbintree == 0) return false; q.push(tmp->left); } else isbintree = 0; if (tmp->right) { if (isbintree == 0) return false; q.push(tmp->right); } else isbintree = 0; } } return true;}
二叉树中两个节点的最近公共祖先
要求考虑以下三种种情况,给出解决方案,并解决:
1:二叉树每个节点有parent(三叉链)
相当于转换成链表求交点问题
2:二叉树是搜索二叉树。
直接找比他们最大还大的节点
3:就是普通二叉树。(尽可能实现时间复杂度为(N ))
通过路径来求
class Solution {public: /** * @param root: The root of the binary search tree. * @param A and B: two nodes in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */bool GetNodePath(TreeNode* cur, TreeNode* node, vector<TreeNode*>& l){ if (cur == node) { l.push_back(cur); return true; } if(cur==NULL) return false; l.push_back(cur); bool found = false; if (!found && cur->left) found = GetNodePath(cur->left, node, l); if (!found && cur->right) found = GetNodePath(cur->right, node, l); if (!found) l.pop_back(); return found;} TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) { // write your code here if(root==A||root==B||root==NULL) return root; vector<TreeNode*> path1; GetNodePath(root,A,path1); vector<TreeNode*> path2; GetNodePath(root,B,path2); int size=path1.size()>path2.size()?path2.size():path1.size(); int i=0; TreeNode* ret=NULL; for(;i<size;i++) { if(path1[i]==path2[i]) ret=path1[i]; else break; } return ret; } };
阅读全文
0 0
- 子树/最近公共祖先
- 最近公共祖先LCA
- 最近公共祖先(LCA)
- 最近公共祖先
- Lca 最近公共祖先
- 【最近公共祖先】Tree
- LCA----最近公共祖先
- 最近公共祖先问题
- LCA (最近公共祖先)
- POJ1330(最近公共祖先)
- 最近公共祖先
- 最近公共祖先模版
- 最近公共祖先问题
- 最近公共祖先
- 最近公共祖先
- 最近公共祖先问题
- POJ1330最近公共祖先
- LCA最近公共祖先
- GridView长按短按冲突
- Java的一些小总结
- Comparable与Comparator的区别
- DAY45 数据库--MySQL2
- $("#id")[0]问题
- 子树/最近公共祖先
- unicode,ansi,utf-8,unicode big endian编码区别 --篇2
- linux ssh 免密登录
- 进程管理--之三
- NotePad++作为texlive编辑器的安装及配置
- Python3 网络编程
- 【Spring】IOC底层原理
- 例说数据结构&STL(十一)——hash_map/unordered_map
- POJ2502 subway