105. Construct Binary Tree from Preorder and Inorder Travers
发布时间:2020-12-14 04:38:04 所属栏目:大数据 来源:网络整理
导读:Given preorder and inorder traversal of a tree,construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example,given preorder =?[3,9,20,15,7]inorder = [9,3,7] Return the following binary tree: 3 / 9 20
Given preorder and inorder traversal of a tree,construct the binary tree. Note: For example,given preorder =?[3,9,20,15,7] inorder = [9,3,7] Return the following binary tree: 3 / 9 20 / 15 7 public TreeNode buildTree(int[] preorder,int[] inorder) { int preLength = preorder.length; int inLength = inorder.length; return buildTree(preorder,preLength-1,inorder,inLength-1); } public TreeNode buildTree(int[] pre,int preStart,int preEnd,int[] in,int inStart,int inEnd){ if(inStart > inEnd || preStart > preEnd) return null; int rootVal = pre[preStart]; int rootIndex = 0; for(int i = inStart; i <= inEnd; i++){ if(in[i] == rootVal){ rootIndex = i; break; } } int len = rootIndex - inStart; TreeNode root = new TreeNode(rootVal); root.left = buildTree(pre,preStart+1,preStart+len,in,inStart,rootIndex-1); root.right = buildTree(pre,preStart+len+1,preEnd,rootIndex+1,inEnd); return root; } 题解: ? 1 / 2 3 / / 4 5 6 7 public TreeNode buildTree(int[] preorder,inEnd); return root; } ? 以上转自?https://www.cnblogs.com/springfor/p/3884034.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |