Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
inorder = [9,3,15,20,7] postorder = [9,15,7,20,3]
Return the following binary tree:
3 / 9 20 / 15 7
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { Map<Integer, Integer> mymap = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { mymap.put(inorder[i], i); } return helper(0, inorder.length - 1, 0, postorder.length - 1, postorder, mymap); } private TreeNode helper(int inLeft, int inRight, int postLeft, int postRight, int[] postorder, Map<Integer, Integer> mymap) { if (inLeft > inRight) { return null; } TreeNode cur = new TreeNode(postorder[postRight]); int index = mymap.get(postorder[postRight]); int leftSize = index - inLeft; // postRight for left just add up leftSize cur.left = helper(inLeft, index - 1, postLeft, postLeft + leftSize - 1, postorder, mymap); cur.right = helper(index + 1, inRight, postLeft + leftSize, postRight - 1, postorder, mymap); return cur; } }
[LC] 106. Construct Binary Tree from Inorder and Postorder Traversal
原文:https://www.cnblogs.com/xuanlu/p/12170929.html