首页 > 代码库 > [leetcode] Construct Binary Tree from Inorder and Postorder Traversal

[leetcode] 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.

https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/

 

思路:递归求解,后序遍历可以获得根节点,然后根据根节点在中序排列中的位置分出左右子树。

 

public class Solution {    public TreeNode buildTree(int[] inorder, int[] postorder) {        if (postorder.length == 0 || inorder.length == 0)            return null;        TreeNode res = build(inorder, postorder, inorder.length);        return res;    }    private TreeNode build(int[] in, int[] post, int len) {        if (len <= 0)            return null;        TreeNode root = new TreeNode(post[len - 1]);        int idx = -1;        for (int i = 0; i < len; i++) {            if (in[i] == post[len - 1])                idx = i;        }        root.left = build(Arrays.copyOfRange(in, 0, idx), Arrays.copyOfRange(post, 0, idx), idx);        root.right = build(Arrays.copyOfRange(in, idx + 1, len), Arrays.copyOfRange(post, idx, len - 1), len - 1 - idx);        return root;    }        public static void main(String[] args) {        new Solution().buildTree(new int[] { 9, 3, 15, 20, 7 }, new int[] { 9, 15, 7, 20, 3 });    }}
View Code