Construct Binary Tree from Preorder and Inorder Traversal(前序遍歷和中序遍歷樹構造二叉樹)...

weixin_33866037發表於2017-09-15

問題

Given preorder and inorder traversal of a tree, construct the binary tree.
** Notice
You may assume that duplicates do not exist in the tree.

Have you met this question in a real interview? Yes

ExampleGiven in-order [1,2,3]
and pre-order [2,1,3]
, return a tree:

7341549-d2aa500e7c9a83a2.png

分析

7341549-f4a7ec00993b3fcd.png

以這個二叉樹為例,前序是1245367,中序是4251637。我們知道前序的第一個一定是根結點。所以先把1找出來,然後在中序裡邊找到1,那麼1左邊的一定是1的左子樹,1右邊的一定是1的右子樹,然後遞迴即可。裡邊需要使用到前序,中序和後序的知識,大家自行查閱資料學習。

程式碼

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     *@param preorder : A list of integers that preorder traversal of a tree
     *@param inorder : A list of integers that inorder traversal of a tree
     *@return : Root of a tree
     */
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        // write your code here
        return buildTree(preorder,0,preorder.length-1,inorder,0,inorder.length-1);
    }
    private TreeNode buildTree(int[] preorder,int pleft,int pright, int[] inorder,int ileft,int iright){
        if(pleft>pright||ileft>iright){
            return null;
        }
        int i=preorder[pleft];
        TreeNode node=new TreeNode(i);
        int index=ileft;
        while(inorder[index]!=i){
            index++;
        }
        int leftLength=index-ileft;
        node.left=buildTree(preorder,pleft+1,pleft+leftLength,inorder,ileft,index-1);
        node.right=buildTree(preorder,pleft+leftLength+1,pright,inorder,index+1,iright);
        return node;
    }
}

相關文章