lintcode: Search Range in Binary Search Tree

来源:互联网 发布:javascript:void(0) 编辑:程序博客网 时间:2024/05/27 14:12

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;    }};
0 0
原创粉丝点击