lintcode 11. Search Range in Binary Search Tree

image.png

其实任何一种遍历都可以,只是中序遍历方便于剪枝。

中序遍历:本题涉及到二叉查找树的按序输出,应马上联想到二叉树的中序遍历

/**
 * 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 searchRange(TreeNode * root, int k1, int k2) {
        // write your code here
        vector ans;
        if(root == NULL) return ans;
        inorder(root, ans, k1, k2);
        return ans;
    }
private:
    void inorder(TreeNode* root, vector& nums,int k1, int k2){
        if(root == NULL) return;
        inorder(root->left, nums, k1, k2);
        if(root->val >= k1 && root->val <= k2){
            nums.push_back(root->val);
        }
        inorder(root->right, nums, 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: 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 searchRange(TreeNode * root, int k1, int k2) {
        // write your code here
        vector ans;
        if(root == NULL) return ans;
        inorder(root, ans, k1, k2);
        return ans;
    }
private:
    void inorder(TreeNode* root, vector& nums,int k1, int k2){
        if(root == NULL) return;
        if(root->val >= k1) inorder(root->left, nums, k1, k2);
        if(root->val >= k1 && root->val <= k2){
            nums.push_back(root->val);
        }
        if(root->val <= k2) inorder(root->right, nums, k1, k2);
    }
};

你可能感兴趣的:(lintcode 11. Search Range in Binary Search Tree)