LeetCode:M-105. Construct Binary Tree from Preorder and Inorder Traversal

LeetCode链接


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

/**
 * 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) {
        return sub(preorder, inorder, 0, 0, preorder.length-1);
    }
    int findIndex(int label, int[] inorder, int ins, int ine){
        for(int i=ins; i<=ine; i++){
            if(label==inorder[i])
                return i;
        }
        
        return -1;
    }
    
    TreeNode sub(int[] preorder, int[] inorder, int index, int ins, int ine){
        
        if(ins>ine)
            return null;
        
        int label = preorder[index];
        int centerIndex = findIndex(label, inorder, ins, ine);
        
        TreeNode left = sub(preorder, inorder, index+1, ins, centerIndex-1);
        TreeNode right = sub(preorder, inorder, index+(centerIndex-ins)+1, centerIndex+1, ine);
        
        TreeNode node = new TreeNode(label);
        node.left = left;
        node.right = right;
        
        return node;
    }
}


你可能感兴趣的:(二叉树,LeetCode,Medium)