【數據結構】根據前序遍歷與中序遍歷重建樹

  直接衝代碼

package algorithm_tree;

import java.util.Arrays;

/**
 * @Author: xc
 * @Date: 2019/11/12 20:26
 * @Description:
 * public class TreeNode {
 *   int val;
 *   TreeNode left;
 *   TreeNode right;
 *
 *   TreeNode(int x) {
 *       val = x;
 *   }
 *}
 **/
public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {

//        List<Object> preList = Arrays.stream(pre).boxed().collect(Collectors.toList());
//        List<Object> inList = Arrays.stream(in).boxed().collect(Collectors.toList());
//        int firstIndex = 0;
//        for(int i = 0;i<inList.size();i++){
//            if (preList.get(0) ==inList.get(i) ){
//                firstIndex = i;
//                break;
//            }
//        }
//        List left = inList.subList(0,firstIndex);
//        List right = inList.subList(firstIndex+1,inList.size());
//        preList.remove(0);
//        TreeNode node = new TreeNode((Integer)inList.get(firstIndex));
//        /*遍歷左子樹*/
//        TreeNode temp = node;
//        while(!left.isEmpty()){
//
//        }
//        /*遍歷右子樹*/
//        temp = node;
//        while(!right.isEmpty()){
//
//        }
        /**
         * 重建樹,根據原理,從前序遍歷的第一個元素值在中序遍歷中的值,然後劃分左右子樹
         * 例如:前序遍歷序列{1,2,4,7,3,5,6,8} 中序遍歷序列{4,7,2,1,5,3,8,6}。
         * 那麼第一個根節點就是1,中序遍歷得到左右子樹數組{4,7,2},{5,3,8,6}
         *                 1
         *            /         \
         *        {4,7,2}   {5,3,8,6}
         *  之後再在子樹數組中找到根節點以及他的左右子樹
         *  前序中的1已經用掉了,下一位是2,那麼得到{4,7},{}爲2的左右子樹數組
         *                 1
         *            /         \
         *          2       {5,3,8,6}
         *       /     \
         *    {4,7}   NULL
         *    如此直到左右子樹數組爲空即遍歷完了
         * 上面註釋的方法在遍歷左子樹和右子樹時要不斷地創建新的左右子數組,而且需要不斷地用到while(子樹數組不爲空)這個條件
         * 於是想到遞歸*/
        if (pre.length==0 || in.length==0) return null;
        TreeNode rootNode = new TreeNode(pre[0]);

        for (int i = 0;i<in.length;i++){
            if (pre[0] == in[i]){
                /*這個copyOfRange是左閉右開的,要注意取值*/
                int[] left = Arrays.copyOfRange(in,0,i);
                int[] right = Arrays.copyOfRange(in,i+1,in.length);

                rootNode.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),left);
                rootNode.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),right);
            }
        }

        return rootNode;



    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章