[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
程序员文章站
2022-07-14 14:13:39
...
这题比较智障,本质上就是找到第一个节点,输入的两个节点一个比它大,另一个比它小。
1. 如果两个节点都比当前节点大,往右走
2. 如果两个节点都比当前节点小,往左走
3. 出现第一个一个节点比当前大,另一个比当前小。返回
注意这里有一个edge case,就是这类题目,ancestor可以是节点自己。所以碰到任意一个节点与两个节点的其中一个相等,返回本身即可。给出代码如下吧:
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (p == null || q == null) return p == null ? q : p;
TreeNode minor = p.val < q.val ? p : q;
TreeNode major = minor == p ? q : p;
while (root != null) {
if (root.val == q.val || root.val == p.val) return root;
if (root.val > q.val && root.val > p.val) {
root = root.left;
} else if (root.val < p.val && root.val < q.val) {
root = root.right;
} else {
return root;
}
}
return root;
}
上一篇: 波兰表达式(递归)
下一篇: 贪心问题求解思路(总结)
推荐阅读
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
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
-
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 C++
-
Leetcode 235. Lowest Common Ancestor of a Binary Search Tree