Problem
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.
Example
If k1 = 10 and k2 = 22, then your function should return [12, 20, 22].
20
/ \
8 22
/ \
4 12
Note
重点是:根据BST的性质,先左后根最后右。
另一重点是,helper函数和main函数都要用的的参数,记得在main函数外层定义。
Solution
public class Solution {
private ArrayList<Integer> result;
public ArrayList<Integer> searchRange(TreeNode root, int k1, int k2) {
// write your code here
result = new ArrayList<Integer>();
Searchfunc(root, k1, k2);
return result;
}
public void Searchfunc(TreeNode root, int k1, int k2) {
if (root == null) {
return;
}
if (root.val > k1) {
Searchfunc(root.left, k1, k2);
}
if (root.val >= k1 && root.val <= k2) {
result.add(root.val);
}
if (root.val < k2) {
Searchfunc(root.right, k1, k2);
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。