Share the joy
This is a practice for Tree. The idea is to find all results in a certain range in BST.
- import java.util.ArrayList;
- import java.util.List;
- import util.Tree;
- public class FindRangeInBst {
- public static void main(String[] args) {
- Tree bst = Tree.getBst();
- List<Tree> result = new ArrayList<Tree>();
- findRangeInBst(bst, 11, 16, result);
- System.out.println(result.toString());
- }
- public static void findRangeInBst(Tree tree, int min, int max,
- List<Tree> result) {
- if (tree == null) {
- return;
- }
- if (tree.value >= min && tree.value <= max) {
- result.add(tree);
- findRangeInBst(tree.left, min, max, result);
- findRangeInBst(tree.right, min, max, result);
- } else if (tree.value < min) {
- findRangeInBst(tree.right, min, max, result);
- } else {
- findRangeInBst(tree.left, min, max, result);
- }
- }
- }