Recursive 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[] preorder, int[] inorder) {
            return buildTree(preorder, inorder, 0, preorder.length - 1, 0, preorder.length - 1);
        }
        
        public TreeNode buildTree(int[] preorder, int[] inorder, int pbeg, int pend, int ibeg, int iend) {
            
            if(pbeg > pend || ibeg > iend) {
                return null;
            }
            
            TreeNode head = new TreeNode(preorder[pbeg]);
            int i = ibeg;
            while(i < inorder.length && inorder[i] != head.val) {
                i++;
            }
            
            head.left = buildTree(preorder, inorder, pbeg + 1, pbeg + i - ibeg, ibeg, i - 1);
            head.right = buildTree(preorder, inorder, pbeg + i - ibeg + 1, pend, i + 1, iend);
            
            return head;
        }
    }
    

Log in to reply
 

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