zoukankan      html  css  js  c++  java
  • [LeetCode] 938. Range Sum of BST

    Description

    Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive).

    The binary search tree is guaranteed to have unique values.

    Example 1:

    Input: root = [10,5,15,3,7,null,18], L = 7, R = 15
    Output: 32
    

    Example 2:

    Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10
    Output: 23
    

    Note:

    1. The number of nodes in the tree is at most 10000.
    2. The final answer is guaranteed to be less than 2^31.

    Analyse

    获取BST(Binary Search Tree)中居于LR之间的节点之和(包括LR)

    BST的中序遍历即为递增的有序序列,我写的第一个版本用了中序遍历,但只是简单的判断节点的值是否处于LR之间,未用到BST的性质,这样可以达到faster than 98.11%

    int rangeSumBST(TreeNode* root, int L, int R) {
        if (root == NULL) return 0;
        int sum = 0;
    
        inOrder(root, L, R, sum);
        return sum;
    }
    
    void inOrder(TreeNode* root, int L, int R, int& sum)
    {
        if (root == NULL) {return;}
    
        inOrder(root->left, L, R, sum);
    
        if (root-> val >= L && root->val <= R)
        {
            sum += root->val;
        }
    
        inOrder(root->right, L, R, sum);
    }
    

    更好的做法是利用BST的性质减少一部分路径的遍历,贴上leetcode上的代码

    如果遍历的当前节点的valLR之间,递归加上该节点的两个子节点的值
    当前节点的val > L && val > R,递归加上该节点的左节点的值
    当前节点的val < L && val < R,递归加上该节点的右节点的值

    int rangeSumBST(TreeNode* root, int L, int R) {
        if(root == NULL) 
            return 0;
        int sum = 0;
        if(root->val >= L && root->val <= R)
            return (root->val + rangeSumBST(root->left, L, R) +
                rangeSumBST(root->right, L, R));
        else if(root->val > L && root->val > R)
            return rangeSumBST(root->left, L, R);
        else if (root->val < L && root->val < R)
            return rangeSumBST(root->right, L, R);
    }
    
  • 相关阅读:
    Ignoring HTTPS certificates
    利用Httponly提升web应用程序安全性
    HttpUrlConnection java.net.SocketException: Software caused connection abort: recv failed
    DISPOSE_ON_CLOSE 和 EXIT_ON_CLOSE 的区别
    Swing多线程
    攒机知识积累
    数组最大子数组和
    fork()详解
    理解Socket编程【转载】
    STM32F407_LED代码
  • 原文地址:https://www.cnblogs.com/arcsinw/p/10279652.html
Copyright © 2011-2022 走看看