Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* n1, TreeNode* n2) {
- if(root == NULL) return NULL;
- if((root->val == n1->val)|| (root->val == n2->val)){
- return root;
- }
- TreeNode* leftans = lowestCommonAncestor(root->left,n1,n2);
- TreeNode* rightans = lowestCommonAncestor(root->right,n1,n2);
- if(leftans != NULL && rightans != NULL ) return root;
- else if(leftans != NULL && rightans ==NULL) return leftans;
- else if(leftans == NULL && rightans !=NULL) return rightans;
- else return NULL;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment