java根據先序列和後續建二叉樹


public class Main {

    private static java.util.Arrays Arrays;

    static  public TreeNode reConstructBinaryTree(int [] pre, int [] in) {
        if(pre.length==0){
            return null;
        }
        TreeNode q=new TreeNode(pre[0]);
        int i;
        for( i=0;i<in.length;i++){
            if(in[i]==pre[0]){
                break;
            }
        }
        q.left=reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i));
        q.right=reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length));
        return q;
    }
    static void dfs(TreeNode q){
        if(q==null)return;
        dfs(q.left);
        System.out.println(q.val);
        dfs(q.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 home=reConstructBinaryTree(pre,in);
        dfs(home);
    }
}

 

發佈了136 篇原創文章 · 獲贊 46 · 訪問量 11萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章