2ms Java Solution -- easy to understand


  • 0
    I

    public class Solution {

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        if (inorder.length==0) return null;
        return dfs(inorder, 0, inorder.length-1, postorder, postorder.length-1);
    }
    public TreeNode dfs(int[] inorder, int start, int end, int[] postorder , int cur){
        if (start>end) return null;
        if (start==end) return new TreeNode(inorder[start]);
        TreeNode root = new TreeNode(postorder[cur]);
        int i = end;
        while(inorder[i]!=postorder[cur]){
            i--;
        }
        root.right = dfs(inorder,i+1, end , postorder, cur-1);
        root.left = dfs(inorder, start, i-1, postorder, cur -(end-i)-1);
        return root;
    }
    

    }


Log in to reply
 

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