Thursday, August 4, 2016

235. Lowest Common Ancestor of a Binary Search Tree

Well, a quite easy problem.

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->val > p->val && root->val > q->val) return lowestCommonAncestor(root->left, p, q);  
14:      if (root->val < p->val && root->val < q->val) return lowestCommonAncestor(root->right, p, q);  
15:      return root;  
16:    }  
17:  };  

No comments:

Post a Comment