Movatterモバイル変換


[0]ホーム

URL:


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

Sign up
Appearance settings

Commitecda904

Browse files
author
applewjg
committed
ConstructBinaryTreefromPreorderandInorderTraversal
Change-Id: Ifde5ecad675fc6b7f00fcf9d41ed414edb3547bb
1 parent481a615 commitecda904

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines 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+
publicclassSolution {
25+
publicTreeNodebuildTree(int[]preorder,int[]inorder) {
26+
if(inorder.length ==0 ||preorder.length ==0 ||inorder.length !=preorder.length)returnnull;
27+
returnbuildTreeRe(preorder,0,inorder,0,preorder.length);
28+
}
29+
publicTreeNodebuildTreeRe(int[]preorder,ints1,int[]inorder,ints2,intsize) {
30+
if (size <=0 )returnnull;
31+
TreeNodenode =newTreeNode(preorder[s1]);
32+
if (size ==1)returnnode;
33+
intpos =s2;
34+
while (pos <= (s2 +size -1)) {
35+
if (inorder[pos] ==preorder[s1])break;
36+
++pos;
37+
}
38+
intleftlen =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+
returnnode;
42+
}
43+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp