235. Lowest Common Ancestor of a Binary Search Tree
程序员文章站
2022-07-14 14:13:51
...
LeetCode里关于树的题似乎很多都用递归做比较好,这道题用常规方法比较麻烦,但是用递归就很简洁(看了答案才醒悟……)
递归解法如***意题中给出的是BST,左子节点的键值<根节点的键值<右子节点的键值):
/**
* 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 (p->val<root->val && q->val<root->val) return lowestCommonAncestor(root->left, p, q);
else if (p->val>root->val && q->val>root->val) return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
上一篇: 随机森林算法&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