首页 > 代码库 > [leetcode] Construct Binary Tree from Preorder and Inorder Traversal
[leetcode] Construct Binary Tree from Preorder and Inorder Traversal
题目:
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { int len=preorder.length; if(len==0) return null; TreeNode root=new TreeNode(preorder[0]); if(len==1) return root; int index=0; for(int i=0;i<inorder.length;i++){ if(inorder[i]==preorder[0]){ index=i; break; } } if(index>0){ int []preleft=new int[index]; int []inleft=new int[index]; System.arraycopy(preorder,1,preleft,0,index); System.arraycopy(inorder,0,inleft,0,index); root.left=buildTree(preleft,inleft); } if(len-index-1>0){ int []preright=new int [len-index-1]; System.arraycopy(preorder,index+1,preright,0,len-index-1); int []inright=new int [len-index-1]; System.arraycopy(inorder,index+1,inright,0,len-index-1); root.right=buildTree(preright,inright); } return root; }}
[leetcode] Construct Binary Tree from Preorder and Inorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。