题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 
题目链接:

 

 

package com.sunshine.OFFER66_SECOND;

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

    TreeNode(int x) {
        val = x;
    }
}

 

 

package com.sunshine.OFFER66_SECOND;

import org.junit.Test;

public class A4_reConstructBinaryTree {

    @Test
    public void test() {
        int[] pre = {1, 2, 4, 7, 3, 5, 6, 8};
        int[] in = {4, 7, 2, 1, 5, 3, 8, 6};
        TreeNode root = reConstructBinaryTree(pre, in);
        TreeUtility.printTreeOfLine(root);
    }


    int[] pre;
    int[] in;
    int pos = 0;

    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        if (in.length == 0 || pre.length == 0) {
            return null;
        }
        this.pre = pre;
        this.in = in;
        TreeNode root = createTreeNode(0, in.length - 1);
        return root;
    }

    private TreeNode createTreeNode(int left, int right) {
        if (left > right) {
            pos--;
            return null;
        }
        if (left == right) {
            TreeNode newCode = new TreeNode(in[left]);
            return newCode;
        }
        for (int i = left; i <= right; i++) {
            if (pre[pos] == in[i]) {
                TreeNode cur = new TreeNode(pre[pos]);
                pos++;
                cur.left = createTreeNode(left, i - 1);
                pos++;
                cur.right = createTreeNode(i + 1, right);
                return cur;
            }
        }
        return null;
    }
}

 

package com.sunshine.OFFER66_SECOND;

import java.util.LinkedList;

public class TreeUtility {

    //按行打印
    public static void printTreeOfLine(TreeNode root) {
        LinkedList<TreeNode> queue = new LinkedList<>();
        LinkedList<TreeNode> nextQueue = new LinkedList<>();
        queue.add(root);
        nextQueue.add(root);
        while (!nextQueue.isEmpty()) {
            nextQueue.clear();
            while (!queue.isEmpty()) {
                TreeNode cur = queue.poll();
                if(null == cur){
                    System.out.print("#" + " ");
                    continue;
                }
                System.out.print(cur.val + " ");
                nextQueue.add(cur.left);
                nextQueue.add(cur.right);
            }
            queue.addAll(nextQueue);
            System.out.println();
        }

    }
}

 

posted on 2019-08-27 11:02  MoonBeautiful  阅读(190)  评论(0编辑  收藏  举报