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); } };
相关文章推荐
- AVL树-自平衡二叉查找树(Java实现)
- C语言二叉树的非递归遍历实例分析
- 使用C语言构建基本的二叉树数据结构
- 一波二叉树遍历问题的C++解答实例分享
- 举例讲解C语言程序中对二叉树数据结构的各种遍历方式
- C++非递归队列实现二叉树的广度优先遍历
- PHP实现的线索二叉树及二叉树遍历方法详解
- C#使用前序遍历、中序遍历和后序遍历打印二叉树的方法
- C#非递归先序遍历二叉树实例
- C++将二叉树转为双向链表及判断两个链表是否相交
- C++非递归建立二叉树实例
- C语言实现找出二叉树中某个值的所有路径的方法
- C++实现二叉树遍历序列的求解方法
- C语言实现二叉树遍历的迭代算法
- C语言 二叉树的链式存储实例
- C++实现查找二叉树中和为某一值的所有路径的示例
- 用C语言判断一个二叉树是否为另一个的子结构
- C++实现二叉树非递归遍历方法实例总结
- C++二叉树结构的建立与基本操作
- 深入遍历二叉树的各种操作详解(非递归遍历)