您的位置:首页 > 编程语言 > Go语言

Algorithms—105.Construct Binary Tree from Preorder and Inorder Traversal

2015-07-16 13:00 621 查看
思路:根据前序先找出节点,然后去中序找出左右,依次递归。

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, inorder,0,preorder.length-1,0,inorder.length-1);
}
public TreeNode build(int[] preorder, int[] inorder,int ps,int pe,int is,int ie){
if(ps>pe){
return null;
}
int val=preorder[ps];
TreeNode node=new TreeNode(val);
int i = is;
for (; i <=ie; i++) {
if (inorder[i]==val) {
break;
}
}
int rang=i-is;
node.left=build(preorder, inorder,ps+1,ps+rang,is,i-1);
node.right=build(preorder,inorder,ps+rang+1,pe,i+1,ie);
return node;

}
}


耗时:360ms,中游

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: