Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

106. 从中序与后序遍历序列构造二叉树 #70

Open
FE-Sadhu opened this issue Jun 26, 2022 · 0 comments
Open

106. 从中序与后序遍历序列构造二叉树 #70

FE-Sadhu opened this issue Jun 26, 2022 · 0 comments

Comments

@FE-Sadhu
Copy link
Owner

题目

思路:

思路和 105. 从前序与中序遍历序列构造二叉树 一样,都是找到左子树和右子树的中、后序节点,然后递归。

后序遍历的值的结果 === [[左子树的前序遍历结果], [右子树的前序遍历结果],根节点]

中序遍历的值的结果 === [[左子树的中序遍历结果],根节点,[右子树的中序遍历结果]]

我们方法的定义是,输入一个二叉树的后序遍历结果、中序遍历结果,返回构建好的二叉树的根节点。

所以我们可以先根据 左子树的后序/中序遍历结果 求出左子树,同样再求出右子树,最终拼接上根节点就是我们想要的结果了。

代码实现:

var buildTree = function(inorder, postorder) {
    if(!inorder.length) return null;
    const root = postorder[postorder.length -1];
    const rootIndexInInorder = inorder.findIndex(i => i === root);
    const leftTreeInorder = inorder.slice(0, rootIndexInInorder);
    const rightTreeInorder = inorder.slice(rootIndexInInorder + 1);
    const leftTreePostorder = postorder.slice(0, leftTreeInorder.length);
    const rightTreePostorder = postorder.slice(leftTreeInorder.length, -1);
    const node = new TreeNode(root);
    node.left = buildTree(leftTreeInorder, leftTreePostorder);
    node.right = buildTree(rightTreeInorder, rightTreePostorder);
    return node;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant