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

513. 找树左下角的值 #17

Open
zpc7 opened this issue Jul 31, 2022 · 0 comments
Open

513. 找树左下角的值 #17

zpc7 opened this issue Jul 31, 2022 · 0 comments
Labels
中等 LeetCode 难度定级

Comments

@zpc7
Copy link
Owner

zpc7 commented Jul 31, 2022

513. 找树左下角的值

var findBottomLeftValue = function (root) {
    let curVal //将要返回的值
    let curHeight = 0; // 当前遍历在树结构的第几层

    const dfs = (root, height) => {
        // 空节点,返回
        if (!root) {
            return;
        }
        height++;
        // 先左后右
        dfs(root.left, height);
        dfs(root.right, height);
        // 上面是先左后右, 在执行左边的时候, 下面会 先 更改curHeight, 所以右边的时候不会进入条件
        if (height > curHeight) {
            curHeight = height;
            curVal = root.val;
        }
    }

    dfs(root, 0);
    return curVal;

};

// 示例代码
const data = {
    val: 2,
    left: {
        val: 1
    },
    right: {
        val: 3
    }
}

// dfs 执行顺序:
// 1. 执行dfs(left)之前 height = 1, root = data 
// 2. 执行dfs(left), 遇到新的dfs(left) 之前 root = {val:1} height = 2
// 3. 执行新的dfs(left), 此时root 是undefined 返回
// 4. 执行第2中的 dfs(right), 此时root 是undefined 返回
// 5. 回到第2, 去执行dfs(right)后面的代码, 更新curHeight = 2, curVal = 1
// 6. 回到第1, 去执行dfs(right), 此时root = data, height = 1
// 7. 执行dfs(left)前, height = 2, root = (val:3)
// 8. 同样的undefined的判断...省略
// 9.  回到第1, 执行dfs(right)后面的代码, 此时不满足height > curHeight, 不会进条件

findBottomLeftValue(data)
@zpc7 zpc7 added 中等 LeetCode 难度定级 JS labels Jul 31, 2022
@zpc7 zpc7 removed the JS label Aug 13, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
中等 LeetCode 难度定级
Projects
None yet
Development

No branches or pull requests

1 participant