-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path105.BuildTree.cs
47 lines (42 loc) · 1.62 KB
/
105.BuildTree.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// 105. Construct Binary Tree from Preorder and Inorder Traversal
// Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary
// tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.
// Example 1:
// Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
// Output: [3,9,20,null,null,15,7]
// Example 2:
// Input: preorder = [-1], inorder = [-1]
// Output: [-1]
// Constraints:
// 1 <= preorder.length <= 3000
// inorder.length == preorder.length
// -3000 <= preorder[i], inorder[i] <= 3000
// preorder and inorder consist of unique values.
// Each value of inorder also appears in preorder.
// preorder is guaranteed to be the preorder traversal of the tree.
// inorder is guaranteed to be the inorder traversal of the tree.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
public class Solution {
public TreeNode BuildTree(int[] preorder, int[] inorder) {
if(preorder is null || !preorder.Any() ||
inorder is null || !inorder.Any())
return null;
TreeNode root = new TreeNode(preorder[0]);
int middle = Array.IndexOf(inorder, preorder[0]);
root.left = BuildTree(preorder[1..(middle+1)], inorder[..middle]);
root.right = BuildTree(preorder[(middle+1)..], inorder[(middle+1)..]);
return root;
}
}