首页 > 代码库 > 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.
方法
依据树的中序遍历和后序遍历,来恢复树,使用递归的思想。
TreeNode getTree(int[] inorder, int inStart, int inEnd, int[] postorder, int postStart, int postEnd) { if (inStart >= inEnd) { return null; } int cur = postorder[postEnd - 1]; TreeNode root = new TreeNode(cur); int i = 0; int j = inStart; while(inorder[j] != cur) { j++; i++; } root.left = getTree(inorder, inStart, inStart + i, postorder, postStart, postStart + i); root.right = getTree(inorder, inStart + i + 1, inEnd, postorder, postStart + i, postEnd - 1); return root; } public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder == null) { return null; } int len = inorder.length; return getTree(inorder, 0, len, postorder, 0, len); }
Construct Binary Tree from Inorder and Postorder Traversal
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。