Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit ecda904

Browse filesBrowse files
author
applewjg
committed
ConstructBinaryTreefromPreorderandInorderTraversal
Change-Id: Ifde5ecad675fc6b7f00fcf9d41ed414edb3547bb
1 parent 481a615 commit ecda904
Copy full SHA for ecda904

File tree

Expand file treeCollapse file tree

1 file changed

+43
-0
lines changed
Open diff view settings
Filter options
Expand file treeCollapse file tree

1 file changed

+43
-0
lines changed
Open diff view settings
Collapse file
+43Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/*
2+
Author: Andy, nkuwjg@gmail.com
3+
Date: Jan 16, 2015
4+
Problem: Construct Binary Tree from Preorder and Inorder Traversal
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
7+
Notes:
8+
Given preorder and inorder traversal of a tree, construct the binary tree.
9+
Note:
10+
You may assume that duplicates do not exist in the tree.
11+
12+
Solution: Recursion.
13+
*/
14+
15+
/**
16+
* Definition for binary tree
17+
* public class TreeNode {
18+
* int val;
19+
* TreeNode left;
20+
* TreeNode right;
21+
* TreeNode(int x) { val = x; }
22+
* }
23+
*/
24+
public class Solution {
25+
public TreeNode buildTree(int[] preorder, int[] inorder) {
26+
if(inorder.length == 0 || preorder.length == 0 || inorder.length != preorder.length) return null;
27+
return buildTreeRe(preorder, 0, inorder, 0, preorder.length);
28+
}
29+
public TreeNode buildTreeRe(int[] preorder, int s1, int[] inorder, int s2, int size) {
30+
if (size <= 0 ) return null;
31+
TreeNode node = new TreeNode(preorder[s1]);
32+
if (size == 1) return node;
33+
int pos = s2;
34+
while (pos <= (s2 + size - 1)) {
35+
if (inorder[pos] == preorder[s1]) break;
36+
++pos;
37+
}
38+
int leftlen = pos - s2;
39+
node.left = buildTreeRe(preorder, s1 + 1, inorder, s2, leftlen);
40+
node.right = buildTreeRe(preorder, s1 + leftlen + 1, inorder, pos + 1, size - leftlen - 1);
41+
return node;
42+
}
43+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.