Simple java Solution using dfs


  • 0
    D
    /**
     * 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[] preorder, int[] inorder) {
            return dfs(0,0,inorder.length-1,preorder,inorder);
        }
        private TreeNode dfs(int prestart,int instart,int inend,int[] preorder,int[] inorder){
            if(prestart>preorder.length-1||instart>inend) return null;
            TreeNode root=new TreeNode(preorder[prestart]);
            int inindex=0;
            for(int i=instart;i<=inend;i++){
                if(inorder[i]==root.val){
                    inindex=i;
                }
            }
            root.left=dfs(prestart+1,instart,inindex-1,preorder,inorder);
            root.right=dfs(prestart+inindex-instart+1,inindex+1,inend,preorder,inorder);
            return root;
        }
    }

Log in to reply
 

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