One Leetcode per day-938. Scope of binary search tree and [in-order traversal]

Insert picture description here
Main idea: In-order traversal

/**
 * 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;
    }
    
}

Guess you like

Origin blog.csdn.net/weixin_41041275/article/details/111468002
Recommended