解法一:前序遍历
对于二叉搜索树进行前序遍历可以得到一个升序数列,然后根据上下限从升序序列中取数求和。
emmm其实直接在遍历的时候就根据范围求和计算会更加快,但前序遍历的思想不变。
/*** 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) {List<Integer> list = new LinkedList<>();preOrder(root, list);int sum = 0;for (Integer i : list) {if (i < L) {continue;}if (i > R) {break;}sum += i;}return sum;}private void preOrder(TreeNode root, List<Integer> list) {if (root == null) {return;}if (root.left != null) {preOrder(root.left, list);}list.add(root.val);if (root.right != null) {preOrder(root.right, list);}}}
