[LeetCode]Lowest Common Ancestor of a Binary Search Tree
来源:互联网 发布:cad制图软件下载 编辑:程序博客网 时间:2024/05/02 04:53
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 2
and 8
is 6
. Another example is LCA of nodes 2
and 4
is 2
, since a node can be a descendant of itself according to the LCA definition.
[思路]根据二叉树的特点,最小的公共祖先就是在两个点值之间的根节点。特别要注意p,q两个点的大小是不确定的。
/** * 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 min = p->val>q->val?q->val:p->val; int max = p->val>q->val?p->val:q->val; while(true){ if(root->val>=min&&root->val<=max) break; if(root->val<min){ root = root->right; } if(root->val>max){ root = root->left; } } return root; }};
0 0
- leetcode 235: Lowest Common Ancestor of a Binary Search Tree
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree
- leetcode: Lowest Common Ancestor of a Binary Search Tree
- [leetcode][dfs] 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
- [leetcode] Lowest Common Ancestor of a Binary Search Tree
- LeetCode Lowest Common Ancestor of a Binary Search Tree
- leetCode(38):Lowest Common Ancestor of a Binary Search Tree
- leetcode-235-Lowest Common Ancestor of a Binary Search Tree
- [LeetCode]Lowest Common Ancestor of a Binary Search Tree
- Leetcode: Lowest Common Ancestor of a Binary Search Tree
- leetcode[235]:Lowest Common Ancestor of a Binary Search Tree
- Lowest Common Ancestor of a Binary Search Tree-leetcode
- 【leetcode】Lowest Common Ancestor of a Binary Search Tree
- 【Leetcode】Lowest Common Ancestor of a Binary Search Tree
- leetcode 75:Sort Colors
- [LeetCode][Java] Sort Colors
- 自定义View
- 最大区间重叠.
- Android5.0环境配置--从ubuntu安装到环境配置再到xp虚拟机的安装
- [LeetCode]Lowest Common Ancestor of a Binary Search Tree
- nginx 统计日志访问ip个数
- PostgreSQL数据库
- 黑马程序员--异常
- [LeetCode]Delete Node in a Linked List
- 黑马程序员—— 4,二维数组,面向对象,制作帮助文档,静态代码块,构造代码块,构造函数,单例设计模式
- 【试水CAS-4.0.3】第04节_CAS服务端通过数据库认证用户
- uva11235(RMQ问题)
- Qt中PostgreSQL数据库驱动插件的编译