Skip to content

Commit 856d835

Browse files
committed
Create 235. Lowest Common Ancestor of a Binary Search Tree.cpp
This solution is also valid for the general binary tree
1 parent 6f4aa5f commit 856d835

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13+
if(!root || root == p || root == q) return root;
14+
TreeNode *left = lowestCommonAncestor(root->left, p, q);
15+
TreeNode *right = lowestCommonAncestor(root->right, p, q);
16+
if(left && right) return root;
17+
return left ? left : right;
18+
}
19+
};

0 commit comments

Comments
 (0)