zoukankan      html  css  js  c++  java
  • LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

    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
  • 相关阅读:
    学习使用&运算符
    企业发放的奖金根据利润提成。
    取一个整数a从右端开始的47位。
    jQuery Select操作大集合
    js 获取某年某月的最后一天
    sql 语句区分大小写查询
    js 冒泡排序
    一个初学者的程序自学计划
    JWNL体验
    (转)GIS相关的SCI、EI期刊
  • 原文地址:https://www.cnblogs.com/pegasus923/p/8449213.html
Copyright © 2011-2022 走看看