二叉查找树中搜索区间

给定两个值 k1 和 k2(k1 < k2)和一个二叉查找树的根节点。找到树中所有值在 k1 到 k2 范围内的节点。即打印所有x (k1 <= x <= k2) 其中 x 是二叉查找树的中的节点值。返回所有升序的节点值。

如果有 k1 = 10 和 k2 = 22, 你的程序应该返回 [12, 20, 22].

    20
   /  \
  8   22
 / \
4   12
/**
 * 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
        vector<int> res;
        helper(root,k1,k2,res);
        return res;
    }
    void helper(TreeNode* root,int k1,int k2,vector<int>&res){
        if(root==NULL) return;
        if(root->val<=k2&&root->val>=k1){
            helper(root->left,k1,k2,res);
            res.push_back(root->val);
            helper(root->right,k1,k2,res);
        } 
        else if(root->val>k2) helper(root->left,k1,k2,res);
        else helper(root->right,k1,k2,res);
    }
};


你可能感兴趣的:(二叉查找树中搜索区间)