Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions bangdori/Path Sum.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} targetSum
* @return {boolean}
*/
var hasPathSum = function (root, targetSum) {
let answer = false;

const dfs = (tree, curr) => {
if (tree.left) dfs(tree.left, curr + tree.left.val);
if (tree.right) dfs(tree.right, curr + tree.right.val);
if (!tree.left && !tree.right && curr === targetSum) {
answer = true;
return;
}
};
Comment on lines +17 to +24
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

재귀는 탈출조건을 가장 상단에 적는다고 알고있는데 아래에 배치하셨네요 이러면 리프노드에서 한단계 더 밑으로 내려가서 검사를 진행한 이후에 진행이 될거같은데 맞나요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. 자식이 있다. -> 메서드 호출
  2. 자식이 없다. -> targetSum과 비교

dfs 함수가 결국 위 두가지로 나뉘기 때문에, 재귀 함수 내부의 배치 순서가 크게 중요하지 않다고 생각했던 것 같습니다.

근데 생각해보니까 함수의 최하단에 배치되어 있어 탈출을하는 경우에도 결국 모든 라인을 해석한 후 탈출하게 되겠네요. 짚어주셔서 감사합니다 ㅎㅎ


if (root) dfs(root, root.val);
return answer;
};
Loading