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. Construct Binary Tree from Inorder and Postorder Traversal #273

Open
Tcdian opened this issue Jul 27, 2020 · 1 comment
Open

106. Construct Binary Tree from Inorder and Postorder Traversal #273

Tcdian opened this issue Jul 27, 2020 · 1 comment
Labels

Comments

@Tcdian
Copy link
Owner

Tcdian commented Jul 27, 2020

106. Construct Binary Tree from Inorder and Postorder Traversal

根据一棵树的中序遍历与后序遍历构造二叉树。

Note

你可以假设树中没有重复的元素。

Example

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
@Tcdian
Copy link
Owner Author

Tcdian commented Jul 27, 2020

Solution

  • JavaScript Solution
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {number[]} inorder
 * @param {number[]} postorder
 * @return {TreeNode}
 */
var buildTree = function(inorder, postorder) {
    if (inorder.length === 0) {
        return null;
    }
    const val = postorder[postorder.length - 1];
    const separator = inorder.indexOf(val);
    const node = new TreeNode(val);
    node.left = buildTree(inorder.slice(0, separator), postorder.slice(0, separator));
    node.right = buildTree(inorder.slice(separator + 1), postorder.slice(separator, postorder.length - 1));
    return node;
};
  • TypeScript Solution
/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function buildTree(inorder: number[], postorder: number[]): TreeNode | null {
    if (inorder.length === 0) {
        return null;
    }
    const val = postorder[postorder.length - 1];
    const separator = inorder.indexOf(val);
    const node = new TreeNode(val);
    node.left = buildTree(inorder.slice(0, separator), postorder.slice(0, separator));
    node.right = buildTree(inorder.slice(separator + 1), postorder.slice(separator, postorder.length - 1));
    return node;
};

@Tcdian Tcdian added the Tree label Jul 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant