Skip to content

Commit 3d0d6c7

Browse files
committed
BuildTreeByPreAndInorder
1 parent fc3b733 commit 3d0d6c7

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
6+
namespace Tree.TreeLib
7+
{
8+
// // Given preorder and inorder traversal of a tree, construct the binary tree.
9+
10+
// // Note:
11+
// // You may assume that duplicates do not exist in the tree.
12+
public class Solution
13+
{
14+
private int[] _preorder; //preorder array
15+
private int[] _inorder; //inorder array
16+
public TreeNode BuildTree(int[] preorder, int[] inorder)
17+
{
18+
_preorder = preorder;
19+
_inorder = inorder;
20+
//if(_preorder.Length==0 || inorder.Length==0) return null;
21+
//if(prorder.Length!=inorder.Length) return null;
22+
return bulidTree(0,0,_inorder.Length-1);
23+
}
24+
//preStart: index of root of tree
25+
//inStart: of inorder tree, inStart ~ root index - 1 -> left tree
26+
//EndStart:of inorder tree, root index + 1 ~ inEnd -> right tree
27+
private TreeNode bulidTree(int preStart, int inStart, int inEnd)
28+
{
29+
if (preStart > _preorder.Length - 1 || inStart > inEnd)
30+
{
31+
return null;
32+
}
33+
TreeNode root = new TreeNode(_preorder[preStart]);
34+
// find the index of current root in inorder.
35+
int inIndex = curRootIndex(inStart, inEnd, root);
36+
root.left = bulidTree(preStart + 1, inStart, inIndex - 1);
37+
//right subtree begins position in preorder
38+
preStart += inIndex - inStart + 1;
39+
root.right = bulidTree(preStart, inIndex + 1, inEnd);
40+
return root;
41+
}
42+
43+
private int curRootIndex(int inStart, int inEnd, TreeNode root)
44+
{
45+
for (int i = inStart; i <= inEnd; i++)
46+
{
47+
if (_inorder[i] == root.val)
48+
{
49+
return i;
50+
}
51+
}
52+
return -1;
53+
}
54+
55+
}
56+
57+
}

0 commit comments

Comments
 (0)