二叉树

重建二叉树:

题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
 
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

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

public class BinaryTree1 {
    public TreeNode reConstructBinaryTree(int[] pre, int[] in) {
        int rootValue = pre[0];
        TreeNode root = new TreeNode(rootValue);
        root.left = null;
        root.right = null;
        int len = in.length;
        if (len == 1 && pre[0] == in[0]) {
            return root;
        }
        int index = 0;
        for (int i = 0; i < len; i++) {
            if (in[i] == rootValue){
                index = i;
                break;
            }
                
        }
        int leftNum = index;
        int rightNum = len - 1 - index;

        if (leftNum > 0) {
            int[] preLeftSub = new int[leftNum];
            System.arraycopy(pre, 1, preLeftSub, 0, leftNum);

            int[] inLeftSub = new int[leftNum];
            System.arraycopy(in, 0, inLeftSub, 0, leftNum);

            root.left = reConstructBinaryTree(preLeftSub, inLeftSub);
        }

        if (rightNum > 0) {

            int[] preRightSub = new int[rightNum];
            System.arraycopy(pre, leftNum + 1, preRightSub, 0, rightNum);

            int[] inRightSub = new int[rightNum];
            System.arraycopy(in, index + 1, inRightSub, 0, rightNum);

            root.right = reConstructBinaryTree(preRightSub, inRightSub);

        }

        return root;

    }
    
    
    
    /**
     * 递归打印出二叉树
     */


    /**
     * 从根结点开始遍历,从树的最高层叶子结点开始输出,从左至右
     * @param node    当前的结点
     */

    void printTree(TreeNode node) {
        if(node == null){
            return;
        }else{
            
            printTree(node.left);
            System.out.print(node.val+"  ");
            printTree(node.right);
            
        }
        
    }
}

测试用例:

import junit.framework.TestCase;
public class BinaryTree1Test extends TestCase{
    public void test(){
        BinaryTree1 bt = new BinaryTree1();
        int[] a ={1,2,3,4,5,6,7};
        int[] b ={3,2,4,1,6,5,7};
        bt.printTree(bt.reConstructBinaryTree(a, b));
    }
}

 

posted @ 2015-07-07 11:49  疾风剑  阅读(170)  评论(0编辑  收藏  举报