GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/code/lc105.java at master · mJackie/leetcode

Expand file tree

/

lc105.java

Copy path
More file actions
More file actions

Latest commit

 

History

History
History
53 lines (50 loc) · 2.18 KB
/

lc105.java

Copy path

File metadata and controls

53 lines (50 loc) · 2.18 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
48
49
50
51
52
53
package code;
/*
* 105. Construct Binary Tree from Preorder and Inorder Traversal
* 题意:根据先序和中序,构造二叉树
* 难度:Medium
* 分类:Array, Tree, Depth-first Search
* 思路:通过递归的方式,找左节点和右节点
* Tips:思路记一下,自己想不起来。递归的方法,每次把inorder数组分为两半,设置一个pre_index,每次根据pre_index建立节点,向下递归。
*/
public class lc105 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public static void main(String[] args) {
int[] preorder = {3,9,20,15,7};
int[] inorder = {9,3,15,20,7};
buildTree(preorder,inorder);
}
public static TreeNode buildTree(int[] preorder, int[] inorder) {
return recursion(preorder, inorder, 0, 0, inorder.length-1);
}
public static TreeNode recursion(int[] preorder, int[] inorder, int pre_index, int start, int end){ //start,end代表在inorder上搜索的范围
if(start>end || start >inorder.length)
return null;
TreeNode tn = new TreeNode(preorder[pre_index]);
int in_index = 0;
for (int i = 0; i <= end; i++) {
if(preorder[pre_index]==inorder[i])
in_index = i;
}
tn.left = recursion(preorder, inorder, pre_index+1, start, in_index-1);
tn.right = recursion(preorder, inorder, pre_index+in_index-start+1, in_index+1, end); //注意右孩子节点index参数
return tn; //记住函数的返回值的设置,返回Node,递归的构造子树
}
public TreeNode buildTree2(int[] preorder, int[] inorder) {
return helper(preorder, inorder, 0, 0, preorder.length-1);
}
public TreeNode helper(int[] preorder, int[] inorder, int cur, int left, int right){
if(left>right) return null;
TreeNode tn = new TreeNode(preorder[cur]);
int i = left;
for(; i<=right; i++) if(inorder[i]==preorder[cur]) break;
tn.left = helper(preorder, inorder, cur+1, left, i-1);
tn.right = helper(preorder, inorder, cur+i-left+1, i+1, right);
return tn;
}
}
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.