Fork me on github

【每日一题】938. 二叉搜索树的范围和

https://leetcode-cn.com/problems/range-sum-of-bst/

中序遍历,注意递归的写法

/**
 * 中序遍历
 */
class Solution {
    int sum = 0;
    public int rangeSumBST(TreeNode root, int low, int high) {
        if(root == null){
            return 0;
        }
        int left = root.val < low ? 0 : rangeSumBST(root.left, low, high);
        int right = root.val > high ? 0 : rangeSumBST(root.right, low, high);
        int center  = root.val >= low && root.val <= high ? root.val : 0;
        return left + right + center;
    }
}
posted @ 2021-04-27 09:27  zjy4fun  阅读(29)  评论(0编辑  收藏  举报