File tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed
17 - Binary Tree Data Structure Problems/26 - Lowest Common Ancestor of a Binary Tree Expand file tree Collapse file tree 1 file changed +25
-0
lines changed Original file line number Diff line number Diff line change 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 == NULL ) return NULL ;
14+
15+ if (root -> val == p -> val || root -> val == q -> val) return root;
16+
17+ TreeNode* leftAns = lowestCommonAncestor (root -> left, p, q);
18+ TreeNode* rightAns = lowestCommonAncestor (root -> right, p, q);
19+
20+ if (leftAns != NULL && rightAns != NULL ) return root;
21+ else if (leftAns != NULL && rightAns == NULL ) return leftAns;
22+ else if (leftAns == NULL && rightAns != NULL ) return rightAns;
23+ else return NULL ;
24+ }
25+ };
You can’t perform that action at this time.
0 commit comments