Leetcode 235. 二叉搜索树的最近公共祖先 C++
2020-06-29 04:34
141 查看
Leetcode 235. 二叉搜索树的最近公共祖先
题目
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于有根树 T 的两个结点 p、q,最近公共祖先表示为一个结点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(一个节点也可以是它自己的祖先)。”
例如,给定如下二叉搜索树: root = [6,2,8,0,4,7,9,null,null,3,5]
测试样例
示例 1:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 输出: 6 解释: 节点 2 和节点 8 的最近公共祖先是 6。
示例 2:
输入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 输出: 2 解释: 节点 2 和节点 4 的最近公共祖先是 2, 因为根据定义最近公共祖先节点可以为节点本身。
说明:
- 所有节点的值都是唯一的。
- p、q 为不同节点且均存在于给定的二叉搜索树中。
题解
我们可以递归查找,如果当前节点的值小于两个指定节点的值,那么最近公共祖先就在右子树上;如果当前节点的值大于两个指定节点的值,那么最近公共祖先就在左子树上。否则,则其就是最近公共祖先。详细过程见代码
代码
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; }
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
相关文章推荐
- 一天一道LeetCode(八). 235. 二叉搜索树的最近公共祖先 236. 二叉树的最近公共祖先
- Leetcode实战:235.二叉搜索树的最近公共祖先
- leetcode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树BST的最近公共祖先LCA + 深度优先遍历DFS
- Leetcode 235. 二叉搜索树的最近公共祖先
- LeetCode写题历程——235. 二叉搜索树的最近公共祖先
- leetcode_235. Lowest Common Ancestor of a Binary Search Tree 查找二叉搜索树最近公共祖先结点
- [LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先
- (刷题笔记)Leetcode 235.二叉搜索树的最近公共祖先
- leetcode--235. 二叉搜索树的最近公共祖先
- 【Java】LeetCode-剑指Offer-面试题68 - I - 二叉搜索树的最近公共祖先【两种解法】
- LeetCode 235. Lowest Common Ancestor of a Binary Search Tree (二叉搜索树最近的共同祖先)
- leetcode 235 二叉搜索树最近公共祖先
- [剑指offer] 二叉搜索树的最近公共祖先 (C++ 解法)
- 二叉搜索树的最近公共祖先(leetcode)
- Leetcode 236. 二叉树的最近公共祖先 C++
- 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】
- 求LCA最近公共祖先的在线ST算法_C++
- leetcode--236. 二叉树的最近公共祖先