检测一个数组能否表示二叉搜索树(BST)的先序遍历
来源:互联网 发布:电脑桌面文件分类软件 编辑:程序博客网 时间:2024/06/08 08:59
GeeksforGeeks的文章:
http://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
题目大意:
给你一个整形数组
题目分析:
题目只需要你判断可能性。因此,我们需要弄明白BST先序遍历的特点。有几点内容:
- 优先沿左子树往下遍历,元素值逐渐变小
- 当左子树不存在时,跳转到同一层最近的右子树,并进行继续优先遍历左子树。
因此,如果数组
问题的关键:性质1有一个前提条件——不断减小的元素存在下界——跳转的根结点。一旦超过下界,那么就违反了BST的性质。例如:
元素9就是元素6的右孩子,那么6就是9这颗子树沿左子树往下遍历的下界。该例中元素8,7都大于6,所以满足性质1的前提条件。如果改变
bool canRepresentBST(int pre[], int n){ // Create an empty stack stack<int> s; // Initialize current root as minimum possible // value int root = INT_MIN; // Traverse given array for (int i=0; i<n; i++) { // If we find a node who is on right side // and smaller than root, return false if (pre[i] < root) return false; // If pre[i] is in right subtree of stack top, // Keep removing items smaller than pre[i] // and make the last removed item as new // root. while (!s.empty() && s.top()<pre[i]) { root = s.top(); s.pop(); } // At this point either stack is empty or // pre[i] is smaller than root, push pre[i] s.push(pre[i]); } return true;}
0 0
- 检测一个数组能否表示二叉搜索树(BST)的先序遍历
- BST二叉搜索树的建树和先序遍历
- 【BST】根据前序遍历的数组构造搜索二叉树
- 230.leetcode Kth Smallest Element in a BST(medium)[二叉搜索树 先序遍历 栈]
- leetcode 230. Kth Smallest Element in a BST 二叉搜索树BST的中序遍历
- 二叉搜索树的非递归遍历之先序
- 判断一个数组是否是二叉搜索树的后序遍历(java)
- 剑指offer:二叉搜索树的后序遍历序列(判断一个数组是否是二叉搜索树的后续遍历序列)
- BST(二叉搜索树)按层遍历
- 二叉树的遍历(先序/中序/后序,递归/迭代)与搜索
- 搜索二叉树(BST)的实现
- 数组实现根据二叉树的先序遍历和中序遍历构造二叉树
- 前序遍历用一维数组表示的二叉树
- hdu3999 the order of a tree - BST二叉搜索树的前序遍历
- leetcode 501. Find Mode in Binary Search Tree 二叉搜索树BST的中序遍历
- 面试题精选(76):给定BST先序遍历序列,不构造BST的情况下判断BST是否每个node都只有一个child
- 二叉树的先序、中序、后序遍历的JavaScript表示
- 先序、中序、后序遍历二叉树及二叉搜索树的总结
- 高效开发 Android App 的 10 个建议
- NOIP2014部分题解
- iOS--错误集锦--UI控件不显示原因之一
- Unity ReorderableList 可重新排序的列表框使用
- 利用小波融合对由聚焦失败导致的图像模糊进行修复
- 检测一个数组能否表示二叉搜索树(BST)的先序遍历
- GCD介绍与总结
- 黑马程序员_简易版IE浏览器 2.0
- redis+Keepalived实现Redis高可用性(非sentinel)
- OutlineOnePassVF
- 在eclipse中使用struts的regex校验器不起作用
- win 10 下Genymotion安装VirtualBox提示失败的问题
- Android之如何解决Android studio运行出现的HAX kernel modules is not installed
- 7 - VC维度(VC Dimension)-- 衡量模型与样本的复杂度