您的位置:首页 > 其它

lintcode: Search Range in Binary Search Tree

2016-03-22 21:38 204 查看
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.

中序遍历,判断每个key是否在[k1,k2]之间。

/**
* 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: The root of the binary search tree.
* @param k1 and k2: range k1 to k2.
* @return: Return all keys that k1<=key<=k2 in ascending order.
*/
void helper(vector<int> &res,TreeNode* node,int k1,int k2){
if(node->left){
helper(res,node->left,k1,k2);
}

if(node->val>=k1 && node->val<=k2){
res.push_back(node->val);
}

if(node->right){
helper(res,node->right,k1,k2);
}

}

vector<int> searchRange(TreeNode* root, int k1, int k2) {
// write your code here

vector<int> res;

if(root==NULL){
return res;
}

helper(res,root,k1,k2);

return res;
}
};


利用BST的特征,还可以进行剪枝,

/**
* 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: The root of the binary search tree.
* @param k1 and k2: range k1 to k2.
* @return: Return all keys that k1<=key<=k2 in ascending order.
*/
void helper(vector<int> &res,TreeNode* node,int k1,int k2){
if(node->left && node->val>=k1){//
helper(res,node->left,k1,k2);
}

if(node->val>=k1 && node->val<=k2){//
res.push_back(node->val);
}

if(node->right && node->val<=k2){
helper(res,node->right,k1,k2);
}

}

vector<int> searchRange(TreeNode* root, int k1, int k2) {
// write your code here

vector<int> res;

if(root==NULL){
return res;
}

helper(res,root,k1,k2);

return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: