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

112. 路径总和 #77

Open
Geekhyt opened this issue Sep 19, 2021 · 0 comments
Open

112. 路径总和 #77

Geekhyt opened this issue Sep 19, 2021 · 0 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Sep 19, 2021

原题链接

递归

  1. 处理边界,节点不存在时返回 false
  2. 左右子树都不存在时代表是叶子结点,判断是否符合条件
  3. 递归左右子树时进行转换,看能否找到 targetSum - root.val 的路径
const hasPathSum = (root, targetSum) => {
  if (root === null) return false               
  if (root.left === null && root.right === null) {
    return targetSum - root.val === 0
  }
  return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val)
}
  • 时间复杂度: O(n)
  • 空间复杂度: O(H),H 是树的高度
@Geekhyt Geekhyt added the 简单 label Sep 19, 2021
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