Leetcode NO.235 Lowest Common Ancestor of a Binary Search Tree
2015-07-13 06:48
239 查看
本题题目要求如下:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
For example, the lowest common ancestor (LCA) of nodes
Another example is LCA of nodes
since a node can be a descendant of itself according to the LCA definition.
本题乍一看不算简单,其实,只要考虑到BST的特性,还是可以比较容易的得到答案,
首先设定LCA为root,
(1)如果root->val比p,q值都小,LCA要设定为root->right
(2)如果root->val比p,q都大,LCA要设定为root->left
(3)如果root->val在p,q之间,则结束循环,LCA得到最终值:root
用recursive运行上面三步,如果遇到(3)跳出,返回最终值
代码如下:
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined
between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
_______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5
For example, the lowest common ancestor (LCA) of nodes
2and
8is
6.
Another example is LCA of nodes
2and
4is
2,
since a node can be a descendant of itself according to the LCA definition.
本题乍一看不算简单,其实,只要考虑到BST的特性,还是可以比较容易的得到答案,
首先设定LCA为root,
(1)如果root->val比p,q值都小,LCA要设定为root->right
(2)如果root->val比p,q都大,LCA要设定为root->left
(3)如果root->val在p,q之间,则结束循环,LCA得到最终值:root
用recursive运行上面三步,如果遇到(3)跳出,返回最终值
代码如下:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if (root->val < p->val and root->val < q->val) { return lowestCommonAncestor(root->right, p, q); } else if (root->val > p->val and root->val > q->val) { return lowestCommonAncestor(root->left, p, q); } else { return root; } } };
相关文章推荐
- 开始刷leetcode day63:House Robber II
- Qt Quick之StackView详解(1)
- 2015.07.12总结
- #leetcode#Fraction to Recurring Decimal
- 开始刷leetcode day63:Contains Duplicate III
- hexo搭建github静态博客总结
- HTML data属性
- 开始刷leetcode day63:Contains Duplicate II
- 开始刷leetcode day63: Contains Duplicate
- [Leetcode] Two Sum
- 开始刷leetcode day63:Invert Binary Tree
- 开始刷leetcode day63:Implement Queue using Stacks
- 折扣网站分享
- The reference to entity "characterEncoding" must end with the ';' delimiter (Mybatis + Mysql)
- 开机流程、模块管理与loader
- 实体类调用泛型父类中的静态方法中执行CRUD——第一版
- iOS runtime整理
- 使用 jquery 获取一组或者单个 checkbox 的选中状态的值
- 捷的軟體開發流程(CMMI)
- 测试常用网址