1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
function constructFromPrePost(pre: number[], post: number[]): TreeNode | null { function travese(preIndex: number, postIndex: number, N: number) { if (N === 0) return null const root = new TreeNode(pre[preIndex]) if (N === 1) return root
let L = 1 const leftRootIndex = preIndex + 1 for(; L < N; ++L) { if (post[postIndex + L - 1] === pre[leftRootIndex]) break }
root.left = travese(leftRootIndex, postIndex, L) root.right = travese(leftRootIndex + L, L + postIndex, N - L - 1) return root } return travese(0, 0, pre.length) };
|