首页 > 代码库 > 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.
思路很简单:根据后序遍历的序列确定根节点,在中序遍历中找到根节点,将原来的序列分为左右两个部分,递归解决左右两个部分就可以解决这个问题。
Java代码如下:
public class ConstructBinaryTreefromInorderandPostorderTraversal { /** * @Construct Binary Tree from Inorder and Postorder Traversal * link:https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/ * idea:递归 */ class TreeNode{ int val; TreeNode left; TreeNode right; public TreeNode(int x) { val=x; } } class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder.length==0){ return null; } TreeNode node=createTree(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1); return node; } public TreeNode createTree(int[] inorder,int inbegin,int inend,int[] postorder,int postbegin,int postend){ if(inbegin>inend){ return null; } int root=postorder[postend]; int index=0; for(int i=inbegin;i<=inend;i++){ if(root==inorder[i]){ index=i; break; } } int len=index-inbegin; TreeNode left=createTree(inorder, inbegin, index-1, postorder, postbegin, postbegin+len-1); TreeNode right=createTree(inorder, index+1, inend, postorder, postbegin+len, postend-1); TreeNode node=new TreeNode(root); node.left=left; node.right=right; return node; } } }
Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。