[LeetCode] Lowest Common Ancestor of a Binary Tree

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 };

 

posted @ 2015-07-13 15:36  jianchao-li  阅读(169)  评论(0编辑  收藏  举报