解法一:前序遍历

对于二叉搜索树进行前序遍历可以得到一个升序数列,然后根据上下限从升序序列中取数求和。
emmm其实直接在遍历的时候就根据范围求和计算会更加快,但前序遍历的思想不变。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. class Solution {
  11. public int rangeSumBST(TreeNode root, int L, int R) {
  12. List<Integer> list = new LinkedList<>();
  13. preOrder(root, list);
  14. int sum = 0;
  15. for (Integer i : list) {
  16. if (i < L) {
  17. continue;
  18. }
  19. if (i > R) {
  20. break;
  21. }
  22. sum += i;
  23. }
  24. return sum;
  25. }
  26. private void preOrder(TreeNode root, List<Integer> list) {
  27. if (root == null) {
  28. return;
  29. }
  30. if (root.left != null) {
  31. preOrder(root.left, list);
  32. }
  33. list.add(root.val);
  34. if (root.right != null) {
  35. preOrder(root.right, list);
  36. }
  37. }
  38. }