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 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) 
21     {
22         int ip=p->val;
23         int iq=q->val;
24         int imax=max(ip,iq);
25         int imin=ip+iq-imax;
26         TreeNode *h=root;
27         while((imin>h->val)||(imax<h->val))
28             h=(imin>h->val)? h->right:h->left;
29         return h;        
30     }
31 };

二叉排序树找两个节点的最近祖先,从根节点开始,第一个把两个给定节点分开的,就是最近祖先。

posted on 2018-05-24 16:20  高数考了59  阅读(107)  评论(0)    收藏  举报