Recent common ancestor 235- binary search tree

 

 

 1 class Solution {
 2 public:
 3     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
 4         int parentval=root->val;
 5         int pval=p->val;
 6         int qval=q->val;
 7         if((pval>parentval)&&(qval>parentval))
 8         {
 9             return lowestCommonAncestor(root->right,p,q);
10         }
11         else if((pval<parentval)&&(qval<parentval))
12         {
13             return lowestCommonAncestor(root->left,p,q);
14         }
15         else{
16             return root;
17         }
18     }
19     
20 };
View Code

 

Guess you like

Origin www.cnblogs.com/nxnslc-blog/p/12392722.html