938. Range Sum of BST

本文探讨了在给定范围内求解二叉树节点值总和的问题,提供了两种不同的实现方式:一种是采用广度优先搜索策略遍历树;另一种则是使用递归方式简化代码逻辑。通过对比这两种方法,读者可以更好地理解如何高效地解决此类问题。

感觉这里需要遍历几乎所有的元素

 

我写的代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        int res= 0;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        TreeNode cur;
        if( root != null )queue.offer( root );
        while( !queue.isEmpty() ){
            cur = queue.poll();
            int cur_v = cur.val;
            if( cur_v <= L && cur.right != null )queue.offer(cur.right);
            else if( cur_v >= R && cur.left != null)queue.offer(cur.left);
            else {
                if( cur.right != null )queue.offer(cur.right);
                if(cur.left != null)queue.offer(cur.left);
            }
            if( cur_v >= L && cur_v <= R )res += cur_v;              
        }
        return res;
    }
}

再看看人家写的代码&思路:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int rangeSumBST(TreeNode root, int L, int R) {
        if( root == null )return 0;
        if( root.val < L)return rangeSumBST(root.right, L, R);
        if( root.val > R )return rangeSumBST( root.left, L, R );
        return root.val + rangeSumBST(root.right, L, R) + rangeSumBST( root.left, L, R );
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值