【转载】判断整数序列是不是二元查找树的后序遍历结果
来源:互联网 发布:js处理json 编辑:程序博客网 时间:2024/06/05 00:58
判断整数序列是不是二元查找树的后序遍历结果
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
ANSWER:
This is an interesting one. There is a traditional question that requires the binary tree to be re-constructed from mid/post/pre order results. This seems similar. For the problems related to (binary) trees, recursion is the first choice.
In this problem, we know in post-order results, the last number should be the root. So we have known the root of the BST is 8 in the example. So we can split the array by the root.
题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。
如果是返回true,否则返回false。
例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
ANSWER:
This is an interesting one. There is a traditional question that requires the binary tree to be re-constructed from mid/post/pre order results. This seems similar. For the problems related to (binary) trees, recursion is the first choice.
In this problem, we know in post-order results, the last number should be the root. So we have known the root of the BST is 8 in the example. So we can split the array by the root.
int isPostorderResult(int a[], int n) { return helper(a, 0, n-1);}int helper(int a[], int s, int e) { if (e==s) return 1; int i=e-1; while (a[e]>a[i] && i>=s) i--; if (!helper(a, i+1, e-1)) return 0; int k = i; while (i>=s && a[e]<a[i]) i--; if (i < s) return helper(a, s, k); else return 0;}
Maybe another solution is also fine:
int helper(int a[], int s, int e, int max, int min) Similar to http://blog.csdn.net/taoqick/article/details/16992475
0 0
- 【转载】判断整数序列是不是二元查找树的后序遍历结果
- 9.判断整数序列是不是二元查找树的后序遍历结果(树)
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 算法讨论(五)--判断整数序列是不是二元查找树的后序遍历结果
- 算法题11 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 9.判断整数序列是不是二元查找树的后序遍历结果
- MS100(9)-判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 9、判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 9、判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 判断整数序列是不是二元查找树的后序遍历结果
- 逗B少年搞程序02 你叫接口是吧
- android手势操作滑动效果触摸屏事件处理
- C语言深度解剖读书笔记
- POJ 3009 图的遍历+DFS+回溯
- oracle vm virtualbox按照Ubuntu
- 【转载】判断整数序列是不是二元查找树的后序遍历结果
- poj 1860 Currency Exchange (SPFA)
- 安装VirtualBox
- am335x修改sd卡cd管脚
- 动态规划 最长公共子序列
- 前端工程师必须掌握的知识点
- 并发控制与事务隔离
- C++中Sort函数使用方法
- android 实战练习 回归手机卫士 一 主界面布局