给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。
样例
如果有 k1 = 10
和 k2 = 22
, 你的程序应该返回 [12, 20, 22]
.
20
/ \
8 22
/ \
4 12
注意:search函数中的vector<int>&result一定要用&,否则主函数中返回的result将为空
最佳答案:
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> searchRange(TreeNode * root, int k1, int k2) {
// write your code here
vector<int>res;
stack<TreeNode*>s;
if(root==NULL||k1>k2)
return res;
TreeNode*p=root;
while(p||!s.empty())
{
if(p)
{ s.push(p);
p=p->left;
}
else
{
p=s.top();
s.pop();
if((p->val>=k1)&&(p->val<=k2))
res.push_back(p->val);
p=p->right;
}
}
return res;
}
};
递归答案:
因为二叉查找树的中序遍历即为从小到大的有序序列。所以可按照中序遍历递归。
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
*/
void search(TreeNode*root,vector<int>&result,int k1,int k2)//&很重要
{ if(root==NULL)
return;
search(root->left,result,k1,k2);//因为二叉查找树的中序遍历即为从小到大的有序序列。
if(root->val<=k2&&root->val>=k1)
result.push_back(root->val);
search(root->right,result,k1,k2);
}
vector<int> searchRange(TreeNode * root, int k1, int k2) {
// write your code here
vector<int>result;
if(root==NULL) return result;
search(root,result,k1,k2);
//reverse(result.begin(),result.end());
return result;
}
};
错误答案:
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> searchRange(TreeNode * root, int k1, int k2) {
// write your code here
vector<int>result;
if(root==NULL) return;//当第一个searchRange(root->left)遇到NULL时便返回result了,轮不到第二个searchRange(root->right)
searchRange(root->left,k1,k2);//所以需要另一个函数。
if(root->val<=k2&&root->val>=k1)
result.push_back(root->val);
searchRange(root->right,k1,k2);
//reverse(result.begin(),result.end());
return result;
}
};