My Java solution


  • 0
    I
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            return buildTree(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
        }
        
        public TreeNode buildTree(int[] inorder, int[] postorder, int ibeg, int iend, int pbeg, int pend) {
            
            if(ibeg > iend || pbeg > pend) {
                return null;
            }
            
            TreeNode head = new TreeNode(postorder[pend]);
            
            int i = ibeg;
            while(inorder[i] != head.val) {
                i++;
            }
            
            head.left = buildTree(inorder, postorder, ibeg, i - 1, pbeg, pbeg + i - 1 - ibeg);
            head.right = buildTree(inorder, postorder, i + 1, iend, pbeg + i - ibeg, pend - 1);
            
            
            return head;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.