重置二叉树

代码实现

package edu.liangman.offer;

/**
* Created by lm on 2017/1/3.
*/
public class RebuldBinTeee {

public static TreeNode bulid(int[] pre,int preStart,int preEnd,int[] in,
int inStart,int inEnd){

if(preStart>preEnd||inStart>inEnd){
return  null;
}
TreeNode root = new TreeNode(pre[preStart]);
for(int i=inStart;i<=inEnd;i++){
if(in[i]==pre[preStart]) {
root.left=bulid(pre,preStart+1,i-inStart+preStart,
in,inStart,i-1);
root.right= bulid(pre,i-inStart+preStart+1,preEnd,
in,i+1,inEnd);
}
}

return root;

}
public static void prePrintTree(TreeNode root){
if(root!=null){
System.out.print(root.val+"  ");
prePrintTree(root.left);
prePrintTree(root.right);
}
}

public static void main(String[] args){
int[] pre ={1,2,4,7,3,5,6,8};
int[] in  ={4,7,2,1,5,3,8,6};
TreeNode root = bulid(pre,0,pre.length-1,in,0,in.length-1);
prePrintTree(root);
}

public static class TreeNode{
private int val;
private TreeNode left;
private TreeNode right;

public TreeNode(int val) {
this.val = val;
this.left = null;
this.right = null;
}

public TreeNode() {

}

public int getVal() {
return val;
}

public void setVal(int val) {
this.val = val;
}

public TreeNode getLeft() {
return left;
}

public void setLeft(TreeNode left) {
this.left = left;
}

public TreeNode getRight() {
return right;
}

public void setRight(TreeNode right) {
this.right = right;
}
}
}


运行结果

• 本文已收录于以下专栏：

举报原因： 您举报文章：重置二叉树 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)