蓝桥杯每日一练——二叉搜索树的最近公共祖先
二叉搜索树的最近公共祖先https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
题目描述:
给定一个二叉搜索树, 找到该树中两个指定节点的最近公共祖先。
leetcode题解这个图画的不错,很容易理解
class Solution {public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { TreeNode* ancestor = root; while (true) { if (p->val val && q->val val) { ancestor = ancestor->left; } else if (p->val > ancestor->val && q->val > ancestor->val) { ancestor = ancestor->right; } else { break; } } return ancestor; }};