Search Range in Binary Search Tree
Question
- lintcode: (11) Search Range in Binary Search Tree
Problem Statement
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
题解 - 中序遍历
中等偏易难度题,本题涉及到二叉查找树的按序输出,应马上联想到二叉树的中序遍历,对于二叉查找树而言,使用中序遍历即可得到有序元素。对每次访问的元素加以判断即可得最后结果,由于 OJ 上给的模板不适合递归处理,新建一个私有方法即可。
- reference
- 前序遍历
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
this.val = val
this.left, this.right = None, None
"""
class Solution:
"""
@param root: The root of the binary search tree.
@param k1 and k2: range k1 to k2.
@return: Return all keys that k1<=key<=k2 in increasing order.
"""
def searchRange(self, root, k1, k2):
# write your code here
ans = []
if root is None:
return ans
queue = [root]
index = 0
while index < len(queue):
if queue[index] is not None:
if queue[index].val >= k1 and \
queue[index].val <= k2:
ans.append(queue[index].val)
queue.append(queue[index].left)
queue.append(queue[index].right)
index += 1
return sorted(ans)