首页 > 代码库 > [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.
https://oj.leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
思路:递归求解,后序遍历可以获得根节点,然后根据根节点在中序排列中的位置分出左右子树。
public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if (postorder.length == 0 || inorder.length == 0) return null; TreeNode res = build(inorder, postorder, inorder.length); return res; } private TreeNode build(int[] in, int[] post, int len) { if (len <= 0) return null; TreeNode root = new TreeNode(post[len - 1]); int idx = -1; for (int i = 0; i < len; i++) { if (in[i] == post[len - 1]) idx = i; } root.left = build(Arrays.copyOfRange(in, 0, idx), Arrays.copyOfRange(post, 0, idx), idx); root.right = build(Arrays.copyOfRange(in, idx + 1, len), Arrays.copyOfRange(post, idx, len - 1), len - 1 - idx); return root; } public static void main(String[] args) { new Solution().buildTree(new int[] { 9, 3, 15, 20, 7 }, new int[] { 9, 15, 7, 20, 3 }); }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。