代码随想录算法训练营第十八天 | 513.找树左下角的值、112.路经总和、106.从中序与后序遍历序列构造二叉树

49 阅读1分钟

513.找树左下角的值

112.路径总和

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

513. 找树左下角的值

  • 注意点:最左边 !== 左子树
// 层序遍历
// 优化点:直接存每层的第一个节点值即可
var findBottomLeftValue = function(root) {
    const q = [];
    const treeMap = [];

    if (!root.left && !root.right)  return root.val;

    q.push(root);
    while (q.length > 0) {
        let len = q.length;
        const values = q.map((item) => item.val);
        treeMap.push([...values]);
        while (len--) {
            const node = q.shift();
            if (node.left) {
                q.push(node.left);
            }
            if (node.right) {
                q.push(node.right);
            }
        }
    }

    if (q.length > 0) {
        const values = q.map((item) => item.val);
        treeMap.push([...values]);
    }

    return treeMap[treeMap.length-1][0];
};

// 优化点:只存更深深度的节点值,且当条件为 > 时,结果就是第一个左节点(同层其余节点由于层数相同不会计入)
var findBottomLeftValue = function(root) {
    const leftMap = [];

    const traverse = (node, h) => {
        if (!node.left && !node.right) {
            leftMap.push({
                v: node.val,
                h
            });
            return;
        }
        
        if (node.left) {
            traverse(node.left, h+1);
        }
        if (node.right) {
            traverse(node.right, h+1);
        }
    }

    traverse(root, 1);

    if (leftMap.length === 0)   return root.val;

    leftMap.sort((a, b) => (b.h - a.h));
    return leftMap[0].v;
};

112. 路径总和

var hasPathSum = function(root, targetSum) {
    const traverse = (node, sum) => {
        if (!node)  return false;
        if (!node.left && !node.right) {
            if (sum + node.val === targetSum) {
                return true;
            } else {
                return false;
            }
        }

        sum += node.val;
        if (node.left)  {
            if (traverse(node.left, sum))   return true;
        }
        if (node.right) {
            if (traverse(node.right, sum))  return true;
        }

        return false;
    }

    return traverse(root, 0);
};

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

思路:左闭右闭区间

var buildTree = function(inorder, postorder) {
    const traverse = (inStart, inEnd, postStart, postEnd) => {
        if (postStart > postEnd || inStart > inEnd)  return null;

        const root = new TreeNode(postorder[postEnd]);

        const inRootIdx = inorder.findIndex((el) => el === postorder[postEnd]);

        root.left = traverse(inStart, inRootIdx - 1, postStart, postStart + (inRootIdx - inStart) - 1);
        root.right = traverse(inRootIdx + 1, inEnd, postStart + (inRootIdx - inStart), postEnd - 1);
        return root;
    }

    return traverse(0, inorder.length-1, 0, postorder.length-1);
};