标签:for 节点 node sys lang system 数字 重建二叉树 pre
/**
* @Date 2020/5/31
* @Author Redo
* @Description 从后序遍历输出中重建二叉树
**/
public class RecoverTreeFromPostOrderOutput {
static class Node{
int data;
Node l;
Node r;
public Node(){};
public Node(int data){
this.data=data;
l=null;
r=null;
}
public static void PostOrderPrint(Node node){
if(node==null)
return;
PostOrderPrint(node.l);
PostOrderPrint(node.r);
System.out.print(node.data+" ");
}
}
private static Node recover(int[] arr,int start,int end){
//该子树为空
if(start>end)
return null;
//末尾数字总是父节点
int head= arr[end];
Node node=new Node(head);
//左子树总是小于父节点,右子树总是大于父节点
int i=start;
for(;i<end;i++){
if(arr[i]>head)
break;
}
node.l= recover(arr,start,i-1);
node.r= recover(arr,i,end-1);
return node;
}
public static Node recover(int[] arr){
return recover(arr,0,arr.length-1);
}
public static void main(String[] args) {
int[] arr={2,4,3,6,8,7,5};
Node node=recover(arr);
Node.PostOrderPrint(node);
}
}
标签:for 节点 node sys lang system 数字 重建二叉树 pre
原文地址:https://www.cnblogs.com/redo19990701/p/13019848.html