首页 > 代码库 > [leetcode]Construct Binary Tree from Inorder and Postorder Traversal
[leetcode]Construct Binary Tree from Inorder and Postorder Traversal
Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
算法:很基础。跟[leetcode]Construct Binary Tree from Preorder and Inorder Traversal类似,根据中序序列和后序序列构建二叉树。
1 public class Solution { 2 public TreeNode buildTree(int[] inorder, int[] postorder) { 3 if(inorder == null || postorder == null || inorder.length != postorder.length || inorder.length == 0) return null; 4 int length = inorder.length ; 5 int val = postorder[length - 1]; 6 int mid = 0; 7 for(int i = 0; i < length; i++){ 8 if(val == inorder[i]){ 9 mid = i;10 break;11 }12 }13 int[] leftInorder = Arrays.copyOfRange(inorder, 0, mid);14 int[] leftPost = Arrays.copyOfRange(postorder, 0, mid);15 int[] rightInorder = Arrays.copyOfRange(inorder, mid + 1, length);16 int[] rightPost = Arrays.copyOfRange(postorder, mid, length - 1);17 TreeNode root = new TreeNode(val);18 root.left = buildTree(leftInorder,leftPost);19 root.right = buildTree(rightInorder, rightPost);20 return root;21 22 }23 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。