leetcode——235——Lowest Common Ancestor of a Binary Search Tree
2016-03-23 22:05
465 查看
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.
Subscribe to see which companies asked this question
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.
Subscribe to see which companies asked this question
/** * 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==nullptr || p==nullptr || q==nullptr) return nullptr; int min = (p->val > q->val ? q->val:p->val); int max = (p->val > q->val ? p->val: q->val); if(max < root->val) return lowestCommonAncestor(root->left, p, q); if (min > root->val) { return lowestCommonAncestor(root->right, p, q); } return root; } };
相关文章推荐
- 逃离迷宫 和 连连看
- Service
- 清除浮动的三种方法(::after/.clear/overflow)
- 阅读笔记--java编程思想第四版 --接口嵌套
- Maven学习-Nexus搭建
- [leetcode 59] Spiral Matrix II--------数组转圈赋值
- EasyRecyclerView 添加header,footer, 上拉加载更多的recyclerview
- ExtJs之Ext.util.CSS
- web前端与后台数据访问的对象封装
- 极大点问题
- linux下weblogic 工程,Spring的Trigger定时器自动shut_down报错信息记录(暂时没有定位到问题)
- 欢迎使用CSDN-markdown编辑器
- Java虚拟机体系结构与类加载器委托机制
- java中的equals方法与"=="运算符解说
- SQL常见笔试面试题
- [原创] 用两个queue实现stack的功能
- Integer做WeakHashMap的Key应注意的问题
- CSS浮动
- 在kali linux206-01版本上安装vmtools一直不能用
- 我理解的--java 单例模式