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

Latest commit

 

History

History
History
23 lines (22 loc) · 973 Bytes

File metadata and controls

23 lines (22 loc) · 973 Bytes
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
package leetcode.tree;
/*
* 根据前序遍历、中序遍历构造二叉树
* */
public class leetcode105 {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length==0||inorder.length==0) return null;
return buildSubTree(preorder,inorder,0,0,inorder.length-1);
}
public TreeNode buildSubTree(int[] preorder, int[] inorder,int preindex,int start,int end) {
if(preindex > preorder.length - 1||start>end) return null;
TreeNode root=new TreeNode(preorder[preindex]); //构建根节点
for(int i=start;i<=end;i++){
if(inorder[i]==preorder[preindex]){
root.right=buildSubTree(preorder,inorder,preindex+i+1-start,i+1,end); //构建右子树,
root.left=buildSubTree(preorder,inorder,preindex+1,start,i-1); //构建左子树,左子树的根节点就在其父亲节点的下一个
break;
}
}
return root;
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.