您的位置:首页 > Web前端

【剑指offer】之二叉搜索树的后序遍历序列

2015-12-18 14:40 183 查看

题目描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出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;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: