您的位置:首页 > 其它

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

2016-07-22 14:21 501 查看

问题描述

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);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode 二叉树