[LeetCode] 938. Range Sum of BST

Posted arcsinw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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);
}


以上是关于[LeetCode] 938. Range Sum of BST的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode --- 938. Range Sum of BST 解题报告

[LeetCode] 938. Range Sum of BST

[LeetCode] 938. Range Sum of BST 二叉搜索树的区间和

Leetcode-938 Range Sum of BST(二叉搜索树的范围和)

LeetCode.938-范围内求二叉搜索树节点值之和(Range Sum of BST)

938. Range Sum of BST