程序笔记   发布时间:2022-07-01  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了938. Range Sum of BST大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

Although this is an easy question, but it is prone to bugs, and the code can be better.

Following is my first solution, didn't use the feature of BST.

private int sum =0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        if(root==null)
            return sum;
        if(root.val>=low&&root.val<=high){
            sum+=root.val;
        }
        rangeSumBST(root.left, low, high);    //whether root.val is in the range or not, this line should be executed, think about why
        rangeSumBST(root.right, low, high);   //whether root.val is in the range or not, this line should be executed, think about why
return sum; }

The following solution use the feature of BST, reduced unnecessary implementations:

    private int sum =0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        if(root==null)
            return sum;
        if(root.val>high)
            rangeSumBST(root.left, low, high);
        else if(root.val<low)
            rangeSumBST(root.right, low, high);
        else{
            sum+=root.val;
            rangeSumBST(root.left, low, high);
            rangeSumBST(root.right, low, high);
        }
        return sum;
    }

The sum in above solution can be removed:

    public int rangeSumBST(TreeNode root, int low, int high) {
        if (root == null)
            return 0;
        if (root.val > high)
            return rangeSumBST(root.left, low, high);
        else if (root.val < low)
            return rangeSumBST(root.right, low, high);
        else {
            return rangeSumBST(root.left, low, high) + rangeSumBST(root.right, low, high) + root.val;
        }
    }

 

大佬总结

以上是大佬教程为你收集整理的938. Range Sum of BST全部内容,希望文章能够帮你解决938. Range Sum of BST所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: