1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| var buildTree = function (inorder, postorder) { const inorderMap = {}; for (let i = 0; i < inorder.length; i++) { inorderMap[inorder[i]] = i; } const recusive = function (inorderLeft, inorderRight, rootIndexinPost) { const rootVal = postorder[rootIndexinPost]; const root = new TreeNode(rootVal); const inorderMid = inorderMap[rootVal]; if (inorderMid > inorderLeft) { root.left = recusive( inorderLeft, inorderMid - 1, rootIndexinPost - (inorderRight - inorderMid) - 1 ); } if (inorderMid < inorderRight) { root.right = recusive(inorderMid + 1, inorderRight, rootIndexinPost - 1); } return root; };
return recusive(0, inorder.length - 1, postorder.length - 1); };
|