首页 > 代码库 > 106. Construct Binary Tree from Inorder and Postorder Traversal
106. 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.
Hide Company Tags
Show Tags
Hide Similar Problems
/** * 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[] inorder, int[] postorder) { return buildSubTree(0, postorder.length -1, postorder, inorder, 0, postorder.length-1); } public TreeNode buildSubTree(int postLeft, int postRight, int[] postorder, int[] inorder, int inLeft, int inRight){ if(postRight < postLeft || inLeft > inRight) return null; int mid = inLeft; TreeNode root = new TreeNode(postorder[postRight]); while(mid <= inRight){ if(postorder[postRight] == inorder[mid]){ root.left = buildSubTree(postLeft, postRight+mid-inRight -1 , postorder, inorder, inLeft, mid-1); root.right = buildSubTree(postRight+mid-inRight, postRight -1, postorder, inorder, mid+1, inRight); } mid++; } return root; }}
106. Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。