선순과 중순으로 두 갈래 나무를 세우다

1546 단어

Construct Binary Tree from Preorder and Inorder Traversal

 
Given preorder and inorder traversal of a tree, construct the binary tree.
Note: You may assume that duplicates do not exist in the tree.
/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
     static int getRootIndexInOrder(int inorder[], int root, int l, int r) {
        while (l <= r) {
            if (inorder[l] != root)
                l++;
            else break;
        }
        return l > r ? -1 : l;
    }

    static TreeNode create(int preorder[], int inorder[], int l1, int r1, int l2, int r2) {
        if (l1 > r1) return null;
        int root = preorder[l1];
        int index = getRootIndexInOrder(inorder, root, l2, r2);
        TreeNode rootNode = new TreeNode(root);

        TreeNode lchild = create(preorder, inorder, l1 + 1, l1 + index - l2, l2, index - 1);
        TreeNode rchild = create(preorder, inorder, l1 + index - l2 + 1, r1, index + 1, r2);

        rootNode.left = lchild;
        rootNode.right = rchild;
        return rootNode;
    }

     public TreeNode buildTree(int[] preorder, int[] inorder) {
        return create(preorder,inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }
}

좋은 웹페이지 즐겨찾기