235. Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:远程oracle数据库拷贝 编辑:程序博客网 时间:2024/06/06 17:59
1、题目描述
输入一个BST和两个节点,返回他们的最低公共祖先。
2、思路
如果两个节点值一个小于或等于根节点值,另一个大于或等于根节点值,则说明它们分别在根节点上或者左右两棵子树上,
所以返回根节点。
如果两个节点都小于根节点值,则从左子树再开始找;
如果两个节点都大于根节点值,则从右子树再开始找。
3、代码
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(!root||!p||!q) return root; if(p->val <= root->val && q->val >= root->val || q->val <= root->val && p->val >= root->val) return root; if(p->val < root->val && q->val < root->val) return lowestCommonAncestor(root->left, p,q); else return lowestCommonAncestor(root->right,p,q); }
阅读全文
0 0
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235.Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235.Lowest Common Ancestor of a Binary Search Tree
- 235.Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree LeetCode
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- 235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]235. Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- [leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
- 图论算法-网络最大流【EK;Dinic】
- mybatis 中哪些数据库支持 useGeneratedKeys="true"
- Android ROM包探索
- ubuntu16.04基本装机
- 03-C#变量的使用
- 235. Lowest Common Ancestor of a Binary Search Tree
- eclipse环境下如何配置tomcat(包含没有Server解决办法)
- Foundation5(二十一)
- cs231n笔记(9+)——非极大值抑制
- Oracle 建立索引及SQL优化
- Mybatis插入语句useGeneratedKeys="true"的用法
- java多线程API的基础之线程的创建
- “”命名空间“System.Web”中不存在类型或命名空间名称“HttpUtility”。是否缺少程序集引用“解决方法
- 使用SiftGPU对两幅图像进行特征点匹配