最近公共祖先
来源:互联网 发布:淘宝品牌男装店 编辑:程序博客网 时间:2024/06/05 21:18
给定一棵二叉树,找到两个节点的最近公共父节点(LCA)。
最近公共祖先是两个节点的公共的祖先节点且具有最大深度。
点题:从下而上,第一次两边都有
/** * 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 root: The root of the binary search tree. * @param A: A TreeNode in a Binary. * @param B: A TreeNode in a Binary. * @return: Return the least common ancestor(LCA) of the two nodes. */ TreeNode * lowestCommonAncestor(TreeNode * root, TreeNode * A, TreeNode * B) { // find target node OR null node if (root == NULL || root->val == A->val || root->val == B->val) { return root; } // find children nodes TreeNode* left = lowestCommonAncestor(root->left, A, B); TreeNode* right = lowestCommonAncestor(root->right, A, B); if (left != NULL && right != NULL) { return root; } // return find results return left == NULL? right : left; }};
阅读全文
0 0
- 最近公共祖先LCA
- 最近公共祖先(LCA)
- 最近公共祖先
- Lca 最近公共祖先
- 【最近公共祖先】Tree
- LCA----最近公共祖先
- 最近公共祖先问题
- LCA (最近公共祖先)
- POJ1330(最近公共祖先)
- 最近公共祖先
- 最近公共祖先模版
- 最近公共祖先问题
- 最近公共祖先
- 最近公共祖先
- 最近公共祖先问题
- POJ1330最近公共祖先
- LCA最近公共祖先
- 最近公共祖先问题
- 数据库第一天
- 我在IT职场超15年:从程序员做到副总,送你21个超实用的职场法则!
- 说话人识别matlab实现
- 一个大胆的想法——尔雅答题
- ## 自学编程,点滴积累##
- 最近公共祖先
- ubuntu执行sudo apt-get update很慢解决办法
- 游标使用介绍
- 数据结构实验之排序四:寻找大富翁
- 隐马尔科夫模型——基本概念
- 一篇杂记
- 服务端I/O性能大比拼:Node、PHP、Java、Go
- Mysql 主从复制配置以及相关的操作
- 二叉树——二叉树的遍历