您的位置:首页 > 其它

【Leetcode】Construct Binary Tree from Inorder and Postorder Traversal

2016-05-21 22:17 423 查看
题目链接:https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

题目:

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

Note:

You may assume that duplicates do not exist in the tree.

思路:

easy

算法

[java] view
plain copy

 





public TreeNode buildTree(int[] inorder, int[] postorder) {  

    if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0) {  

        return null;  

    }  

  

    // 在前序排列中,从头开始查找定位: 第一个既在后序也在中序的元素位置,以及它在后序中的位置  

    int start = -1, pindex = -1;// start是后序中的位置 index是中序的位置  

    for (int i = postorder.length - 1; i >= 0; i--) {  

        int tmp = search(inorder, postorder[i]);  

        if (tmp >= 0) {  

            pindex = tmp;  

            start = i;  

            break;  

        }  

    } // ====end  

    TreeNode root = new TreeNode(postorder[start]);  

    if (inorder.length == 1) {  

        return root;  

    }  

    // 根据index划分中序排列  

    int leftInorder[] = Arrays.copyOfRange(inorder, 0, pindex);  

    int rightInorder[] = Arrays.copyOfRange(inorder, pindex + 1, inorder.length);  

  

    int newpreorder[] = Arrays.copyOfRange(postorder, 0, start);  

  

    root.left = buildTree(leftInorder, newpreorder);  

    root.right = buildTree(rightInorder, newpreorder);  

    return root;  

}  

  

public int search(int nums[], int target) {  

    for (int i = 0; i < nums.length; i++) {  

        if (nums[i] == target)  

            return i;  

    }  

    return -1;  

}  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: