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

左叶子之和-404 #58

Open
sl1673495 opened this issue Jun 7, 2020 · 0 comments
Open

左叶子之和-404 #58

sl1673495 opened this issue Jun 7, 2020 · 0 comments
Labels
DFS 深度优先遍历 二叉树

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jun 7, 2020

计算给定二叉树的所有左叶子之和。

示例:

    3
   / \
  9  20
    /  \
   15   7

在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sum-of-left-leaves
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

用 DFS 的思路,去递归的判断目标节点的左节点是否是叶子节点,如果是的话,就把全局的 sum 加上目标节点的值。然后继续 DFS 目标节点的左右子节点。

let sumOfLeftLeaves = function (root) {
  let sum = 0

  let dfs = (node) => {
    if (!node) return

    if (isLeaf(node.left)) {
      sum += node.left.val
    }

    dfs(node.left)
    dfs(node.right)
  }

  dfs(root)

  return sum
}

function isLeaf(node) {
  return !!node && !node.left && !node.right
}
@sl1673495 sl1673495 added DFS 深度优先遍历 二叉树 labels Jun 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
DFS 深度优先遍历 二叉树
Projects
None yet
Development

No branches or pull requests

1 participant