Skip to content

Latest commit

 

History

History
70 lines (54 loc) · 1.48 KB

20201120.md

File metadata and controls

70 lines (54 loc) · 1.48 KB

Algorithm

105. Construct Binary Tree from Preorder and Inorder Traversal

Description

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

preorder = [3,9,20,15,7]

inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
       if(preorder==null||inorder==null||preorder.length==0||inorder.length==0){
            return null;
        }
        TreeNode treeNode = new TreeNode(preorder[0]);
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==preorder[0]){
                treeNode.left = buildTree(
                        Arrays.copyOfRange(preorder, 1, i+1),
                        Arrays.copyOfRange(inorder, 0 ,i)
                );
                treeNode.right = buildTree(
                        Arrays.copyOfRange(preorder, i+1, preorder.length),
                        Arrays.copyOfRange(inorder,i+1,preorder.length)
                );
            }
        }
        return treeNode;
    }
}

Discuss

Review

Tip

Share