码迷,mamicode.com
首页 > 其他好文 > 详细

【LeetCode 235_二叉搜索树】Lowest Common Ancestor of a Binary Search Tree

时间:2015-07-25 18:17:20      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

解法一:递归

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
 2 {
 3     if (root == NULL || p == NULL || q == NULL)
 4         return NULL;
 5 
 6     if (root->val > p->val && root->val > q->val)
 7         return lowestCommonAncestor(root->left, p, q);
 8     else if (root->val < p->val && root->val < q->val)
 9         return lowestCommonAncestor(root->right, p, q);
10     return root;
11 }

解法二:迭代

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
 2 {
 3     if (root == NULL || p == NULL || q == NULL)
 4         return NULL;
 5 
 6     while (true) {
 7         if (root->val < p->val && root->val < q->val)
 8             root = root->right;
 9         else if (root->val > p->val && root->val > q->val)
10             root = root->left;
11         else
12             break;
13     }
14     return root;
15 }

 

【LeetCode 235_二叉搜索树】Lowest Common Ancestor of a Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/mengwang024/p/4676150.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!