每日一道Leetcode - 938. 二叉搜索树的范围和【中序遍历】

在这里插入图片描述
主要思路:中序遍历

/**
 * 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 {
    
    
    int ans = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
    
    
        if(root==null) return 0;
        rangeSumBST(root.left,low,high);
        if(root.val>=low){
    
    
            if(root.val<=high){
    
    
                ans+=root.val;
            }else{
    
    
                return ans;
            }
        }
        rangeSumBST(root.right,low,high);
        return ans;
    }
    
}

猜你喜欢

转载自blog.csdn.net/weixin_41041275/article/details/111468002