递归遍历即可,root为空时,返回result并没有什么作用,因为我们并不用它,返回它只是因为函数需要一个返回值。
/**
* 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.
*/
vector<int> searchRange(TreeNode* root, int k1, int k2) {
// write your code here
if(root==nullptr)return result;
searchRange(root->left,k1,k2);
if(root->val>=k1&&root->val<=k2)result.push_back(root->val);
searchRange(root->right,k1,k2);
return result;
}
private:
vector<int> result;
};
本文介绍了一种通过递归遍历二叉搜索树的方法来查找指定区间内的所有节点值,并按升序返回这些值。该算法首先检查当前节点是否为空,然后递归地遍历左子树,接着判断当前节点值是否在指定区间内,如果在,则将其加入结果数组中,最后递归地遍历右子树。
261

被折叠的 条评论
为什么被折叠?



