Given preorder and inorder traversal of a tree, construct the binary tree.

来源:互联网 发布:打卡是什么意思网络 编辑:程序博客网 时间:2024/06/06 03:33

题目:利用先序遍历和中序遍历,构造一个二叉树!

例如:

Inorder Traversal:{3,1,7,4,0,5,8,2,6};
Preorder Traversal:{0,1,3,4,7,2,5,8,6};

思路:

1. 先序数组第一个元素为根节点(root);(上例中 root.val= 0)

2. 以root为中心,中序数组分成两个子数组,即为root的左右子树!(上例中分为:subLeft={3,1,7,4}、subRight={5,8,2,6})

3. 在先序序列中 找到对应subLeft在先序数组中的子数组subPreLeft = {1,3,4,7}、

   subRight在先序数组中的字数组subPreRight= {2,5,8,6}

4. 在subPreLeft中的首元素为root.left;

    在subPreRight中的首元素为root.right;

循环上面4个步骤,建立tree!

对应代码:

public static TreeNode buildTreePure(int[] inorder, int[] preorder) {if(inorder.length <= 0 && inorder.length != preorder.length) return null;int inLeft = 0, preLeft = 0,length = inorder.length;TreeNode root = building(inLeft, preLeft, length, inorder, preorder);        return root;}public static TreeNode building(int inLeft, int preLeft, int length, int[] myIn, int[] myPre){if(length>0 && preLeft>=0 && preLeft<myPre.length && inLeft>=0 && inLeft<myIn.length){TreeNode root = new TreeNode(myPre[preLeft]);// get leftLenint leftLen = 0;for(int i = inLeft; i < (inLeft+length); i++){if(myPre[preLeft] == myIn[i]){leftLen = i-inLeft;//System.out.println("i =" + i);break;}}// divide myIn/myPreroot.left  = building(inLeft,preLeft+1,leftLen, myIn, myPre);root.right = building(inLeft+leftLen+1,preLeft+leftLen+1,length-1-leftLen, myIn, myPre);return root;}return null;}






0 0
原创粉丝点击