LintCode 11. Search Range in Binary Search Tree
Description
Given a binary search tree and a range
[k1, k2]
, return node values within a given range in ascending order.
给定一个二叉查找树和范围[k1, k2]
。按照升序返回给定范围内的节点值。
Example
- Example1:
Input:{5},6,10
Output:[]
5
it will be serialized {5}
No number between 6 and 10
- Example2:
Input:{20,8,22,4,12},10,22
Output:[12,20,22]
Explanation:
it will be serialized {20,8,22,4,12}
[12,20,22] between 10 and 22
Challenge
- 当二叉排序树的结构很大,但是取值范围较小,考虑算法的效率。
Submission
二叉排序树,又称为二叉查找树。二叉排序树或者是一棵空树,或者是具有以下性质的二叉树:
- 若其左子树不为空,则左子树上的所有节点的值均小于它的根结点的值;
- 若其右子树不为空,则右子树上的所有节点的值均大于它的根结点的值;
- 左右子树又分别是二叉排序树。
1. 递归方法(中序遍历)
- 原型是中序遍历
中序遍历的递归是先左子树,后根节点,再右子树。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: param root: The root of the binary search tree
* @param k1: An integer
* @param k2: An integer
* @return: return: Return all keys that k1<=key<=k2 in ascending order
*/
vector<int> ans;
void dfs(TreeNode * node, int k1, int k2) {
if(node->left && node->val >= k1){
dfs(node->left, k1, k2);
}
if(node->val >= k1 && node->val <=k2){
ans.push_back(node->val);
}
if(node->right && node->val <=k2){
dfs(node->right, k1, k2);
}
}
vector<int> searchRange(TreeNode * root, int k1, int k2) {
// write your code here
if(root == NULL){
return ans;
}
dfs(root, k1, k2);
return ans;
}
}
2. 非递归方法(中序遍历)
- 非递归的方法需要用到栈进行处理,我们根据(左<根<右)的特点,知道最左子树最下为最小,先全部压入栈内,再依次出栈,进入右子树进行(下一轮的左子树压栈出栈操作。)
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: param root: The root of the binary search tree
* @param k1: An integer
* @param k2: An integer
* @return: return: Return all keys that k1<=key<=k2 in ascending order
*/
vector<int> res;
vector<int> searchRange(TreeNode * root, int k1, int k2) {
// write your code here
if (root == NULL) {
return res;
}
TreeNode * node = root;
stack<TreeNode *> str;
while(!str.empty() || node) {
while(node) {
str.push(node);
node = node->left;
}
if(!str.empty()) {
node = str.top();
str.pop();
if(node->val >= k1 && node->val <= k2) {
res.push_back(node->val);
}
node = node->right;
}
}
return res;
}
};