首页 > 代码库 > [leetcode]Construct Binary Tree from Preorder and Inorder Traversal
[leetcode]Construct Binary Tree from Preorder and Inorder Traversal
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.
算法思路:
根据前序序列和中序序列构建树。递归,没难度。
1 public class Solution { 2 public TreeNode buildTree(int[] preorder, int[] inorder) { 3 if(preorder == null || inorder == null || preorder.length != inorder.length || preorder.length == 0) return null; 4 int val = preorder[0],length = inorder.length; 5 int mid = 0; 6 for(int i = 0; i < length; i++){ 7 if(inorder[i] == val){ 8 mid = i; 9 break;10 }11 }12 int[] leftPre = Arrays.copyOfRange(preorder, 1, mid + 1);13 int[] leftIn = Arrays.copyOfRange(inorder, 0, mid);14 int[] rightPre = Arrays.copyOfRange(preorder, mid + 1, length);15 int[] rightIn = Arrays.copyOfRange(inorder, mid + 1, length);16 TreeNode root = new TreeNode(val);17 root.left = buildTree(leftPre, leftIn);18 root.right = buildTree(rightPre,rightIn);19 return root;20 }21 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。