码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] Lowest Common Ancestor of a Binary Tree

时间:2015-07-13 17:47:40      阅读:87      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!