|
1 | 1 | ## Algorithm
|
2 | 2 |
|
| 3 | +[106. Construct Binary Tree from Inorder and Postorder Traversal](https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/) |
| 4 | + |
3 | 5 | ### Description
|
4 | 6 |
|
5 |
| -### Solution |
| 7 | +Given two integer arrays inorder and postorder where inorder is the inorder traversal of a binary tree and postorder is the postorder traversal of the same tree, construct and return the binary tree. |
| 8 | + |
| 9 | +Example 1: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +``` |
| 14 | +Input: inorder = [9,3,15,20,7], postorder = [9,15,7,20,3] |
| 15 | +Output: [3,9,20,null,null,15,7] |
| 16 | +``` |
6 | 17 |
|
7 |
| -```java |
| 18 | +Example 2: |
| 19 | + |
| 20 | +``` |
| 21 | +Input: inorder = [-1], postorder = [-1] |
| 22 | +Output: [-1] |
| 23 | +``` |
| 24 | + |
| 25 | +Constraints: |
| 26 | + |
| 27 | +- 1 <= inorder.length <= 3000 |
| 28 | +- postorder.length == inorder.length |
| 29 | +- -3000 <= inorder[i], postorder[i] <= 3000 |
| 30 | +- inorder and postorder consist of unique values. |
| 31 | +- Each value of postorder also appears in inorder. |
| 32 | +- inorder is guaranteed to be the inorder traversal of the tree. |
| 33 | +- postorder is guaranteed to be the postorder traversal of the tree. |
| 34 | + |
| 35 | +### Solution |
8 | 36 |
|
| 37 | +```java |
| 38 | +/** |
| 39 | + * Definition for a binary tree node. |
| 40 | + * public class TreeNode { |
| 41 | + * int val; |
| 42 | + * TreeNode left; |
| 43 | + * TreeNode right; |
| 44 | + * TreeNode(int x) { val = x; } |
| 45 | + * } |
| 46 | + */ |
| 47 | +class Solution { |
| 48 | + public TreeNode buildTree(int[] inorder, int[] postorder) { |
| 49 | + if(inorder==null||postorder==null||inorder.length==0||postorder.length==0){ |
| 50 | + return null; |
| 51 | + } |
| 52 | + TreeNode treeNode = new TreeNode(postorder[postorder.length-1]); |
| 53 | + for(int i=0;i<inorder.length;i++){ |
| 54 | + if(inorder[i]==postorder[postorder.length-1]){ |
| 55 | + treeNode.left = buildTree(Arrays.copyOfRange(inorder, 0, i), |
| 56 | + Arrays.copyOfRange(postorder, 0, i)); |
| 57 | + treeNode.right = buildTree(Arrays.copyOfRange(inorder, i+1, inorder.length), |
| 58 | + Arrays.copyOfRange(postorder, i, postorder.length-1)); |
| 59 | + } |
| 60 | + } |
| 61 | + return treeNode; |
| 62 | + } |
| 63 | +} |
9 | 64 | ```
|
10 | 65 |
|
11 | 66 | ### Discuss
|
|
0 commit comments