My 2ms Java Recursive Solution


  • 0
    A

    My 2ms solution

    public class Solution {
    public TreeNode buildTree(int[] inorder, int[] postorder) {
    if (inorder.length == 0 || postorder.length == 0) {
    return null;
    }
    return buildTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1);
    }

    TreeNode buildTree(int[] inorder, int iStart, int iEnd, int[] postorder, int pStart, int pEnd) {
        if (iStart > iEnd) {
        	return null;
        }
        TreeNode root = new TreeNode(postorder[pEnd]);
        int index = iEnd;
        while (inorder[index] != root.val) {
    	index--;
        }
        root.left = buildTree(inorder, iStart, index-1, postorder, pStart,  pStart+(index-iStart)-1);
        root.right = buildTree(inorder,index + 1, iEnd, postorder, pStart+(index-iStart), pEnd -1);
        return root;
    }
    

    }


Log in to reply
 

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