LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

南笙酒味 提交于 2020-04-07 04:00:44

https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0      _4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.


  • 图论题,Tree + 递归。
  • 因为是BST,所以可以类似二分查找。如果两个node都 < root,则从左子树找;如果都 > root,则从右子树找;如果一个 <= ,一个 >= ,则正好在两侧或者就是这个root,说明root就是最小公共祖先。注意,节点可以是自己的最小公共祖先。
  • Lowest Common Ancestor in a Binary Search Tree. | Algorithms
    • https://algorithms.tutorialhorizon.com/lowest-common-ancestor-in-a-binary-search-tree/
 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
13         if (root == nullptr)
14             return root;
15         
16         if (root->val > p->val && root->val > q->val)
17             return lowestCommonAncestor(root->left, p, q);
18         else if (root->val < p->val && root->val < q->val)
19             return lowestCommonAncestor(root->right, p, q);
20         else
21             return root;        
22     }
23 };
View Code

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!