Advertisement
sweet1cris

Untitled

Jan 9th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. public class Solution {
  2.     private int findPosition(int[] arr, int start, int end, int key) {
  3.         int i;
  4.         for (i = start; i <= end; i++) {
  5.             if (arr[i] == key) {
  6.                 return i;
  7.             }
  8.         }
  9.         return -1;
  10.     }
  11.  
  12.     private TreeNode myBuildTree(int[] inorder, int instart, int inend,
  13.             int[] postorder, int poststart, int postend) {
  14.         if (instart > inend) {
  15.             return null;
  16.         }
  17.  
  18.         TreeNode root = new TreeNode(postorder[postend]);
  19.         int position = findPosition(inorder, instart, inend, postorder[postend]);
  20.  
  21.         root.left = myBuildTree(inorder, instart, position - 1,
  22.                 postorder, poststart, poststart + position - instart - 1);
  23.         root.right = myBuildTree(inorder, position + 1, inend,
  24.                 postorder, poststart + position - instart, postend - 1);
  25.         return root;
  26.     }
  27.  
  28.     public TreeNode buildTree(int[] inorder, int[] postorder) {
  29.         if (inorder.length != postorder.length) {
  30.             return null;
  31.         }
  32.         return myBuildTree(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1);
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement