程序中的逻辑错误,该程序计算树中节点的所有值的总和介于L和R之间

问题描述

有人可以告诉我程序中的逻辑错误,我试图在Leetcode上解决它,但是当输入为[10,5,15,3,7,null,18]时,L = 7,R = 15 。它仅计算第一个值10。 目标是添加介于L和R之间(包括两端)的所有值

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

解决方法

我猜

        if(root.val<=R && root.val>=L){
            sum += root.val ;
        }

顺序可能不正确:


class Solution {
    static int sum  ;
    public int rangeSumBST(TreeNode root,int L,int R) {
        if (root == null) {
            return 0 ;
        }

        sum = 0 ;
        AddThem(root,L,R) ;
        return sum ;
    }

    public static int AddThem(TreeNode node,int R) {
        if (node.left != null) {
            AddThem(node.left,R);
        }

        if (node.right != null) {
            AddThem(node.right,R);
        }

        if (node.val >= L && node.val <= R) {
            sum += node.val ;
        }

        return 0;
    }
}

这将通过:

public final class Solution {
    public static final int rangeSumBST(
        final TreeNode root,final int L,final int R
    ) {
        if (root == null) {
            return 0;
        }

        int sum = 0;

        if (root.val > L) {
            sum += rangeSumBST(root.left,R);
        }

        if (root.val < R) {
            sum += rangeSumBST(root.right,R);
        }

        if (root.val >= L && root.val <= R) {
            sum += root.val;
        }

        return sum;
    }
}
,

我认为树是:

       10
  5          15
3   7      n    18

调用sum += AddThem(root.left,R);时,根是5,小于L = 7,因此条件root.val<=R && root.val>=L为假(5 < L = 7)。因此,结果不正确。