You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
else both are not null return the root(curr node), that means left and right are p and q.
classSolution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL || root==p || root==q) return root;
TreeNode* left = lowestCommonAncestor(root->left,p,q);
TreeNode* right = lowestCommonAncestor(root->right,p,q);
if(left == NULL) return right;
elseif(right == NULL) return left;
elsereturn root; // both are not null
}
};
O(N) Time iterative solution
Self Explanatory.
Code
classSolution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
TreeNode* cur = root;
while (true) {
if (p -> val < cur -> val && q -> val < cur -> val) {
cur = cur -> left;
} elseif (p -> val > cur -> val && q -> val > cur -> val) {
cur = cur -> right;
} else {
break;
}
}
return cur;
}
};