Skip to content

Latest commit

 

History

History
68 lines (52 loc) · 1.48 KB

20210202.md

File metadata and controls

68 lines (52 loc) · 1.48 KB

Algorithm

106. Construct Binary Tree from Inorder and Postorder Traversal

Description

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

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

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if(inorder==null||postorder==null||inorder.length==0||postorder.length==0){
            return null;
        }
        TreeNode treeNode = new TreeNode(postorder[postorder.length-1]);
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==postorder[postorder.length-1]){
                treeNode.left = buildTree(Arrays.copyOfRange(inorder, 0, i),
                                         Arrays.copyOfRange(postorder, 0, i));
                treeNode.right = buildTree(Arrays.copyOfRange(inorder, i+1, inorder.length),
                                         Arrays.copyOfRange(postorder, i, inorder.length-1));
            }
        }
        return treeNode;
    }
}

Discuss

Review

Tip

Share