且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[LeetCode] Lowest Common Ancestor of a Binary Tree

更新时间:2022-03-04 19:52:54

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