二叉查找树中搜索区间

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

/**
 * 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<int> searchRange(TreeNode * root, int k1, int k2) {
        // for null node, return empty vector
        vector<int> res;
        
        // return empty vector
        if (root == NULL) {
            return res;
        }
        
        // stack to support mid-order visit
        stack<TreeNode *> st;
        while (root != NULL || !st.empty()) {
            while (root != NULL) {
                st.push(root);
                root = root->left;
            }
            TreeNode * node = st.top();
            st.pop();
            if (node->val <= k2 && node->val >= k1) {
                res.push_back(node->val);
            }
            root = node->right;
        }
        return res;
    }
};

recursive:

/**
 * 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<int> searchRange(TreeNode * root, int k1, int k2) {
        // for null node, return empty vector
        vector<int> res;
        
        // return empty vector
        if (root == NULL) {
            return res;
        }
        
        // recurseve
        midOrderVisit(root, k1, k2, res);
        return res;
    }
    void midOrderVisit(TreeNode* root, int k1, int k2, vector<int> & res) {
        if (root == NULL) {
            return;
        }
        // visit left children
        midOrderVisit(root->left, k1, k2, res);
        // visit root
        if (root->val <= k2 && root->val >= k1) {
            res.push_back(root->val);
        }
        // visit right children
        midOrderVisit(root->right, k1, k2, res);
    }
};

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值