235. Lowest Common Ancestor of a Binary Search Tree
2016-02-21 22:53
267 查看
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.
solution:
运行速度:快
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.
solution:
/** * 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) { int tmp =root->val; if((p->val>tmp&&q->val<tmp)||(p->val<tmp&&q->val>tmp)||p->val==tmp||q->val==tmp) return root; else if(p->val<tmp&&q->val<tmp) return lowestCommonAncestor(root->left,p,q); else return lowestCommonAncestor(root->right,p,q); } };心得:递归
运行速度:快
相关文章推荐
- php中 session和cookie的基本使用
- 秒转时分秒
- Linux内核延时函数
- Vs2015 win10虚拟机启动问题:无法设置UDP端口 解决方法 合集(转载)
- 【转】分析Linux和windows动态库
- [Immutable.js] Using fromJS() to Convert Plain JavaScript Objects into Immutable Data
- LAMP架构搭建与优化(2.8-2.9)
- POJ 3067 Japan(树状数组:求逆序)
- MVP模式在Android开发中的应用
- kali 2.0中msf连接postgres数据库
- c#中的数据类型简介(枚举)
- Microsoft(R) Developer Studio 已停止工作 解决办法(3)
- leetcode刷题,总结,记录,备忘331
- Spring基于jdbcTemplate对数据库的操作
- c中的数据类型
- DataGrid属性介绍
- CSS如何解决子元素越界
- java34.HTTP通信------使用HttpClient进行Get方式通信
- 【tarjan+缩点】BZOJ1051-受欢迎的牛
- 计算几何ACM模板