Advertisement
Guest User

Untitled

a guest
Dec 8th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.90 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * public class TreeNode {
  4.  *     int val;
  5.  *     TreeNode left;
  6.  *     TreeNode right;
  7.  *     TreeNode(int x) { val = x; }
  8.  * }
  9.  */
  10. class Solution {
  11.     public TreeNode buildTree(int[] inorder, int[] postorder) {
  12.         return build(0, postorder.length - 1, inorder, postorder);
  13.     }
  14.    
  15.     public TreeNode build(int start, int end, int[] in, int[] post) {
  16.         if (start > end) return null;
  17.         TreeNode root = new TreeNode(post[post.length - 1]);
  18.         post = Arrays.copyOfRange(post, 0, post.length - 1);
  19.         if (start == end) return root;
  20.         int index = end;
  21.         for (int i = start; i < end; i++) {
  22.             if (in[i] == root.val) {
  23.                 index = i;
  24.             }
  25.         }
  26.         root.right = build(index + 1, end, in, post);
  27.         root.left = build(start, index - 1, in, post);
  28.         return root;
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement