首页 > 其他 > 详细

[LeetCode] Lowest Common Ancestor of a Binary Tree

时间:2015-07-13 17:44:22      阅读:95      评论:0      收藏:0      [点我收藏+]

Well, a follow-up for the problem Lowest Common Ancestor of a Binary Search Tree. However, this time you cannot figure out which subtree the given nodes lie in according to their values. So you need to explicitly find out which subtree they are in. Well, this link contains a damn clever solution, just in 4 lines with explanations! The code is as follows. It is so concise that I can noly copy it...

1 class Solution {
2 public:
3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
4         if (!root || root == p || root == q) return root;
5         TreeNode* left = lowestCommonAncestor(root -> left, p, q);
6         TreeNode* right = lowestCommonAncestor(root -> right, p, q);
7         return !left ? right : !right ? left : root;
8     }
9 };

 

[LeetCode] Lowest Common Ancestor of a Binary Tree

原文:http://www.cnblogs.com/jcliBlogger/p/4643061.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!