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

    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.

    分析:二叉搜索树是排序过的,位于左子树的节点都比父节点小,而位于右子树的节点都比父节点大,我们只需要从树的根节点开始和两个输入的节点比较。如果当前节点的值比两个节点的值都大,那么最低公共祖先一定是在当前节点的左子树中,于是下一步遍历当前节点的左子树。如果当前节点的值比两个节点的值都小,那么最低公共祖先一定在当前节点的右子树中,于是下一步遍历当前节点的右子树。这样在树中从上到下找到的第一个在两个输入节点的值之间的节点,就是最低的公共祖先。

    /**
     * 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 (root->val < p->val && root->val < q->val) {
                return lowestCommonAncestor(root->right, p, q);
            } else if (root->val > p->val && root->val > q->val) {
                 return lowestCommonAncestor(root->left, p, q);
            } else {
                return root;
            }
     
        }
    };
  • 相关阅读:
    gcc编译常用选项
    汇编指令随笔
    VIM简单操作
    Linux编译阻塞型驱动遇到'TASK_NORMAL' undeclared (first use in this function)问题解决办法
    Linux中断流程分析
    Linux驱动开发之LED驱动
    函数(三)
    函数(二)
    文件和函数(一)
    文件处理和字符编码
  • 原文地址:https://www.cnblogs.com/vincently/p/4778970.html
Copyright © 2011-2022 走看看