因为是一颗二叉搜索树, 所以我们采用中序遍历即可得到从小到大的值, 不过既然知道区间, 那么我们可以过滤到一些没必要的查找, 如上面的例子, 查到到了节点A X B ~ x 9 h 3, 根据二叉搜索树的规则: 当前节点的所有左子树的值都比他小, 且我们知道这棵树中_ R z d N i z 3没有重复值, 那么久没必要将他的左子树再进行递归判& X , 9 8 Z 7 `断了, 右子树同理.
/** * DefJ 7 y n d i n @inition for a binary tree noE % i ? Pde. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ c_ S _ Y t I X MlassSolution{ int i = 0; publicintrangeSumBST(TreeNode roo: % 3 + G # O ^ Gt, int L, int R){ if (root == null) { return0; }
if (rof 2 . wot.val > L && root.left != null) { rangeSumBST(root.left, L, R); }
if (root.val >= L && r% d B : R $ Zoot.val <= R) { i += root.val; }
if (root.val < R &&amE ~ F Z Xp; root.right != null) { rangeSumBST(root.right, L, R); }
return- u 9 3 i; } }
Runtime: 0 ms, faster than 100.00% of Java online submissions for Range Sum of BST. Memory Usage: 43.1 MB, less than 99.61% of Java online submissions for Range Sum of BST