lintcode-最近公共祖先-88
来源:互联网 发布:p2p网络借贷论文 编辑:程序博客网 时间:2024/05/20 18:47
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
样例
对于下面这棵二叉树
4 / \3 7 / \ 5 6
LCA(3, 5) = 4
LCA(5, 6) = 7
LCA(6, 7) = 7
/** * 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: TreeNode *lowestCommonAncestor(TreeNode *root, TreeNode *A, TreeNode *B) { if(!root) return NULL; if(root==A) return A; if(root==B) return B; TreeNode *L=lowestCommonAncestor(root->left,A,B); TreeNode *R=lowestCommonAncestor(root->right,A,B); if(L&&R) //如果A和B都在root的子节点中,返回root return root;/* if(!L&&!R) //如果A和B都不在root的子节点中,返回NULL return NULL; if(L&&!R) //如果A在B不在,返回A,告诉上一层A节点已经在该节点的子节点中 return L; if(!L&&R) return R; //实际上这几行代码可以省略 可以包含在最后一段代码中*/ return L?L:R; }};
0 0
- lintcode-最近公共祖先-88
- LintCode-最近公共祖先
- LintCode 最近公共祖先
- LintCode:最近公共祖先
- LintCode:最近公共祖先
- lintcode-最近公共祖先
- 最近公共祖先,lintcode
- lintcode, 最近公共祖先
- 最近公共祖先-LintCode
- lintcode--最近公共祖先
- lintcode----最近公共祖先
- LintCode-剑指Offer-(88)最近公共祖先
- [LintCode]88.最近公共祖先
- lintcode lowest-common-ancestor 最近公共祖先
- [Lintcode]Lowest Common Ancestor 最近公共祖先
- LintCode:M-最近祖先
- 最近公共祖先LCA
- 最近公共祖先(LCA)
- cin.get(),cin,cin.getline()的区别
- 统计硬币
- 自学数据挖掘
- 一个关于“权限正常,但是就是在该文件夹下创建文件失败”
- Opencv腐蚀-erode函数
- lintcode-最近公共祖先-88
- Android自定义控件——手把手教你写出Google样式的ProgressBar
- apriori算法
- 字符流与字节流的区别
- 装饰器模式
- Opencv膨胀-dilate函数
- 【C#】基础知识—初识C#与.Net
- HDU 5446 2015长春站网络赛1010(数论模板题)
- 天天学设计模式1--重新认识面向对象