Beispiel #1
0
    private TreeNode BuildTreeHelper(int[] preorder, int[] inorder, int preL, int preR, int inL, int inR,
                                     Dicitionary <int, int> map)
    {
        if (preL > preR)
        {
            return(null);                                //base case
        }
        TreeNode root    = new TreeNode(preorder[preL]); //create new TreeNode with current root element
        int      index   = map[preorder[preL]];          //the index of root.val in inorder array
        int      numLeft = index - inL;                  //number of nodes at the left subtree of current root

        root.left  = BuildTreeHelper(preorder, inorder, preL + 1, preL + numLeft, inL, index - 1, map);
        root.right = BuildTreeHelper(preorder, inorder, preL + 1 + numLeft, preR, index + 1, inR, map);
        return(root);
    }
 private TreeNode BuildTreeHelper(int[] preorder, int[] inorder, int preL, int preR, int inL, int inR, 
                                   Dicitionary<int,int> map)
 {
     if(preL>preR) return null; //base case
     TreeNode root = new TreeNode(preorder[preL]); //create new TreeNode with current root element
     int index = map[preorder[preL]]; //the index of root.val in inorder array
     int numLeft = index-inL; //number of nodes at the left subtree of current root
     root.left= BuildTreeHelper(preorder, inorder, preL+1, preL+numLeft, inL, index-1, map);
     root.right = BuildTreeHelper(preorder, inorder, preL+1+numLeft, preR, index+1, inR, map);
     return root;
 }