您的位置:首页 > 其它

【leetcode】105. Construct Binary Tree from Preorder and Inorder Traversal

2016-11-04 19:14 369 查看
题目要求:

Given preorder and inorder traversal of a tree, construct the binary tree.

通过先序遍历和中序遍历构造二叉树

思路:先序遍历的第一个结点在中序遍历中找到位置i,然后在先序遍历的位置i左边是左子树,先序遍历的位置i右边是右子树,然后递归的构造左右子树

/**
* 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) {
if(preorder==null||inorder==null||preorder.length==0||inorder.length==0)
{
return null;

}
return buildWithPreIn(preorder,inorder,0,0,inorder.length-1);
}

//根据前序和中序构造二叉树
public TreeNode buildWithPreIn(int[] preorder,int[] inorder,int prestart,int instart,int inend)
{
TreeNode root = null;
for(int i =instart;i<=inend;i++)
{
if(preorder[prestart]==inorder[i])
{
root=new TreeNode(preorder[prestart]);
root.left=buildWithPreIn(preorder,inorder,prestart+1,instart,i-1);
root.right = buildWithPreIn(preorder,inorder,prestart+1+i-instart,i+1,inend);
break;
}
}
return root;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐