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