(WRONG: I was trying to terminate one a target is found in the left subtree or in the right subtree. It is wrong because with the termination condition, you don't know if the other target node is in the same subtree or in the other.)
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 || root == p || root == q) return root;
14: TreeNode *left = lowestCommonAncestor(root->left, p, q);
15: TreeNode *right = lowestCommonAncestor(root->right, p, q);
16: return !left ? right : !right ? left : root;
17: }
18: };
No comments:
Post a Comment