Share my recursive JAVA solution very easy to understand


  • 0
    W
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if (inorder == null || postorder == null || inorder.length == 0 || postorder.length == 0) return null;
    
            int rootIndex = postorder.length - 1;
            TreeNode root = new TreeNode(postorder[rootIndex]);
            
            int rootIndexInorder = 0;
            while (inorder[rootIndexInorder] != postorder[rootIndex]){
                rootIndexInorder++;
            }
            
            int[] leftInorder = Arrays.copyOfRange(inorder, 0, rootIndexInorder);
            int[] rightInorder = Arrays.copyOfRange(inorder, rootIndexInorder + 1, inorder.length);
            
            int[] leftPostorder = Arrays.copyOfRange(postorder, 0, postorder.length - (inorder.length - rootIndexInorder));
            int[] rightPostorder = Arrays.copyOfRange(postorder, postorder.length - (inorder.length - rootIndexInorder), postorder.length - 1);
            
            root.left = buildTree(leftInorder, leftPostorder);
            root.right = buildTree(rightInorder, rightPostorder);
            
            return root;
        }
    }

Log in to reply
 

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