码迷,mamicode.com
首页 > 其他好文 > 详细

[LeetCode] 938. Range Sum of BST

时间:2019-01-16 22:42:40      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:amp   else   第一个   oid   int   null   版本   turn   bin   

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

标签:amp   else   第一个   oid   int   null   版本   turn   bin   

原文地址:https://www.cnblogs.com/arcsinw/p/10279652.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!