【Lowest Common Ancestor of a Binary Tree】cpp
2015-07-14 10:55
417 查看
题目:
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes
代码:
tips:
直接学习大神的思路(http://bookshadow.com/weblog/2015/07/13/leetcode-lowest-common-ancestor-binary-tree/),确实很巧妙。
总体来说,就是分叉找;终止条件是到了叶子或者找到p和q的一个就返回了。
这里有个思维误区,为啥找到p或q的一个就返回了,如果先找到p而q在p的下面呢?那就正好了,反正这俩点如果q在p的下面,那么根据定义p就是p和q的公共祖先。
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______3______ / \ ___5__ ___1__ / \ / \ 6 _2 0 8 / \ 7 4
For example, the lowest common ancestor (LCA) of nodes
5and
1is
3. Another example is LCA of nodes
5and
4is
5, since a node can be a descendant of itself according to the LCA definition.
代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if ( !root || root==p || root==q ) return root; TreeNode* l = Solution::lowestCommonAncestor(root->left, p, q); TreeNode* r = Solution::lowestCommonAncestor(root->right, p, q); if ( l && r ) { return root; } else { return l ? l : r; } } };
tips:
直接学习大神的思路(http://bookshadow.com/weblog/2015/07/13/leetcode-lowest-common-ancestor-binary-tree/),确实很巧妙。
总体来说,就是分叉找;终止条件是到了叶子或者找到p和q的一个就返回了。
这里有个思维误区,为啥找到p或q的一个就返回了,如果先找到p而q在p的下面呢?那就正好了,反正这俩点如果q在p的下面,那么根据定义p就是p和q的公共祖先。
相关文章推荐
- 3.创建一个20个大小的随机数组,找出这组数组的最大值和最小值, 并且标出最大数和最小值的位置
- 利用C++文件流进行数据块的读写
- C++队列用法实例
- Jni中C++和Java的参数传递
- 与C语言不同,JAVA里没有无符号整型
- C++多线程(POSIX)
- 菜鸟学习-C语言函数参数传递详解-结构体与数组
- C语言中Static和Const关键字的的作用 -- 转
- GCC+宏及C++
- 1.将一个有序数组反转
- C++ 整型提升的规则
- C++判断矩形相交的方法
- MFC技术内幕系列之(五)---MFC文档序列化内幕
- MFC技术内幕系列之(四)---MFC消息映射与消息传递内幕
- MFC技术内幕系列之(三)----MFC执行期类型识别与动态创建技术内幕
- C++下用什么矩阵运算库比较好
- C++的global data的位置 及PE 文件中的section的内容
- MFC技术内幕系列之(一)---MFC应用程序“生死因果”内幕
- MFC的工具条和状态栏
- Jni 简单实战 获取c++返回值