【剑指offer】之二叉搜索树的后序遍历序列
2015-12-18 14:40
183 查看
题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
分析:
后序遍历一次,把所有节点压入栈中,然后出栈与数组中的对应值比较。只有所有对应的值相同才输出为true,否则是false.
java代码实现:
题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
分析:
后序遍历一次,把所有节点压入栈中,然后出栈与数组中的对应值比较。只有所有对应的值相同才输出为true,否则是false.
java代码实现:
public class SortedBinTree<T extends Comparable> { static class Node { Object data ; Node parent ; Node left ; Node right ; public Node(Object data, Node parent, Node left, Node right) { super(); this.data = data; this.parent = parent; this.left = left; this.right = right; } @Override public String toString() { return "data[" + data + "]"; } } private Node root ; public SortedBinTree() { root = null; } public Node getRoot() { return root ; } public SortedBinTree(int o) { root = new Node(o, null,null,null); } public void add(T ele) { if(root == null) { root = new Node(ele, null,null,null); } else { Node current = root ; Node parent = null ; int cmp = 0; do { parent = current ; cmp = ele.compareTo(current.data); if(cmp > 0) { //if(ele > current.data) { current = current.right; } else { current = current.left; } } while(current != null); Node newNode = new Node(ele,parent,null,null); if(cmp > 0) { parent.right = newNode ; } else { parent.left = newNode ; } } } Stack stack = new Stack<Node>(); //stack为全局变量 public Stack postInterator(Node root) { if(root.left != null) postInterator(root.left); if(root.right != null) postInterator(root.right); stack.push(root); return stack ; } //判断输入的数组是否是后序遍历 public boolean isPost(Node root, int[]obs) { Stack stack = postInterator(root); int i=0; Iterator iterator = stack.iterator(); while(iterator.hasNext()) { Node node = (Node) iterator.next(); if(i>=obs.length || node==null) { return false; } if(obs[i] != (Integer)node.data) { return false; } i++; } return true; } }
相关文章推荐
- 利用VBA将excel数据表生成JSON文件(utf8)
- 计时器 setInterval clearInterval setTimeout
- react-native 布局
- 转: html5 history api详解~很好的文章
- jquery css3 手机菜单动画综合版
- jsp页面出现两个相同id的标签的读取顺序
- Ext.js5的表格的排序扩展(7)
- 剑指offer 例题
- javascript级联菜单的操作
- BootStrap-DualListBox怎样改造成为双树
- bootstrap 兼容IE6?
- jQuery each
- leetcode(58)Length of Last Word js代码实现
- nodejs基础 -- 常用工具util
- Node.js 究竟是什么?
- DIV+CSS布局和TABLE布局的优缺点讲解
- Ext.js5带子标题的标题的表格(6)
- HTML5实现图片选择并预览
- jQuery设计模式(二)
- JavaScript setTimeout使用闭包功能实现定时打印数值