Skip to content

Latest commit

 

History

History
79 lines (63 loc) · 1.78 KB

20201121.md

File metadata and controls

79 lines (63 loc) · 1.78 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() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
 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, postorder.length-1)
                 );
             }
         }
         return treeNode;
     }
 }

Discuss

注意数组复制 Arrays.copyOfRange(array, 0, i);

Review

Tip

Share