lintcode search-range-in-binary-search-tree 二叉搜索树中搜索区间

问题描述

lintcode

笔记

一开始没有想到怎样利用二叉搜索树的性质简化程序,强行中序遍历了树,如代码1。其实还是应该利用二叉搜索树的性质。中序遍历是一定的

访问左孩子--访问当前节点--访问右孩子

可以做的改进是:

  • k1比当前节点小才去访问左孩子。(可能还遗漏了一些大于k1小于当前节点的数)
  • k2比当前节点大才去访问右孩子。(可能还遗漏了一些大于当前节点小于k2的数)

如代码2。

代码1 暴力中序遍历

/**
 * 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;
        inorder(root, k1, k2, res);
        return res;

    }

    void inorder(TreeNode* root, int k1, int k2, vector<int> &res)
    {
        if (root == NULL)
            return;
        inorder(root->left, k1, k2, res);
        int rootVal = root->val;
        if (rootVal >= k1 && rootVal <= k2)
            res.push_back(rootVal);
        inorder(root->right, k1, k2, res);
    }
};

代码2 利用二叉搜索树的性质

/**
 * 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;
        dfs(root, k1, k2, res);
        return res;
    }

    void dfs(TreeNode *root, int k1, int k2, vector<int> &res)
    {
        if (root == NULL)
            return;
        int rootVal = root->val;
        if (root->left && k1 <= rootVal)
            dfs(root->left, k1, k2, res);
        if (k1 <= rootVal && rootVal <= k2)
            res.push_back(rootVal);
        if (root->right && rootVal <= k2)
            dfs(root->right, k1, k2, res);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值