235. Lowest Common Ancestor of a Binary Search Tree
程序员文章站
2022-07-14 14:14:03
...
1,题目要求
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.
找到两个节点的最小公共祖先节点,即节点2和节点8的最小祖先节点为6,7和9的则是节点8,而2和4的就是2。
2,题目思路
因为题目给定的树为BST,也就是搜索二叉树。因此在进行节点的查找过程中,如果根节点的值都大于节点p和q的值,那么所要查找的节点就一定在该根节点的左子树中;如果根节点的值都小于节点p和q的值,则所要查找的节点就一定在右子树中,如果以上都不是,说明该根节点即为所要查找的根节点,直接返回即可。
3,程序源码
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(!root)
return NULL;
if(root->val > max(p->val, q->val))
return lowestCommonAncestor(root->left, p, q);
else if(root->val < min(p->val, q->val))
return lowestCommonAncestor(root->right,p, q);
else
return root;
}
};
上一篇: 过河问题,C++(非搜索算法实现)
下一篇: 随机森林算法&python应用
推荐阅读
-
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