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

从前序与中序遍历序列构造二叉树 #1068

Open
pwstrick opened this issue Aug 4, 2020 · 0 comments
Open

从前序与中序遍历序列构造二叉树 #1068

pwstrick opened this issue Aug 4, 2020 · 0 comments
Labels
Leetcode Leetcode的题目

Comments

@pwstrick
Copy link
Owner

pwstrick commented Aug 4, 2020

105. 从前序与中序遍历序列构造二叉树

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {number[]} preorder
 * @param {number[]} inorder
 * @return {TreeNode}
 */
var buildTree = function(preorder, inorder) {
    if(preorder.length == 0 || inorder.length == 0) {
        return null;
    }
    if(preorder.length == 1 && inorder.length == 1) {
        return new TreeNode(preorder[0]);
    }
    let rootVal = preorder[0];
    let root = new TreeNode(rootVal);
    let rootPos = inorder.indexOf(rootVal);             //根结点位置
    let leftInorder = inorder.slice(0, rootPos);        //左子树中序遍历
    let rightInorder = inorder.slice(rootPos + 1);      //右子树中序遍历
    let leftPreorder = preorder.slice(1, leftInorder.length + 1);       //左子树前序遍历
    let rightPreorder = preorder.slice(leftInorder.length + 1);         //右子树前序遍历
    root.left = buildTree(leftPreorder, leftInorder);       //左子树
    root.right = buildTree(rightPreorder, rightInorder);    //右子树

    return root;
    // console.log(root);
    // console.log(leftInorder, rightInorder, leftPreorder, rightPreorder);
};
@pwstrick pwstrick added the Leetcode Leetcode的题目 label Aug 4, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Leetcode Leetcode的题目
Projects
None yet
Development

No branches or pull requests

1 participant