你的位置:首页 > Java教程

[Java教程]Lintcode: Search Range in Binary Search Tree


Given two values k1 and k2 (where k1 < k2) and a root pointer to a Binary Search Tree. Find all the keys of tree in range k1 to k2. i.e. print all x such that k1<=x<=k2 and x is a key of given BST. Return all the keys in ascending order.ExampleFor example, if k1 = 10 and k2 = 22, then your function should print 12, 20 and 22.     20    /    \  8      22 /   \4    12

我的做法是inorder traversal的变形,判断是否向左边递归的时候加上判断是否:root.val > k1, 如果否,则不需要继续向左递归;右子树的处理方法类似

 1 public class Solution { 2   /** 3    * @param root: The root of the binary search tree. 4    * @param k1 and k2: range k1 to k2. 5    * @return: Return all keys that k1<=key<=k2 in ascending order. 6   */ 7   public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) { 8     ArrayList<Integer> res = searchRangeRecur(root,k1,k2); 9     return res;10   }11 12   public ArrayList<Integer> searchRangeRecur(TreeNode cur, int k1, int k2){13     ArrayList<Integer> res = new ArrayList<Integer>();14     if (cur==null) return res;15     if (k1>k2) return res;16 17     ArrayList<Integer> left = searchRangeRecur(cur.left,k1,Math.min(cur.val-1,k2));18     ArrayList<Integer> right = searchRangeRecur(cur.right,Math.max(cur.val+1,k1),k2);19 20     res.addAll(left);21     if (cur.val>=k1 && cur.val<=k2) res.add(cur.val);22     res.addAll(right);23 24     return res;25   }26     27 }