티스토리 뷰
leetcode.com/problems/sum-of-left-leaves/
Sum of Left Leaves - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7
There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
var sumOfLeftLeaves = function(root) {
let result = 0;
const dfs = (root, isLeft) => {
if(!root) return;
if(isLeft && !root.left && !root.right) {
result += root.val;
return;
}
dfs(root.left, true);
dfs(root.right, false);
}
dfs(root);
return result;
};
dfs로 순회를 하면서 현재 노드가 부모로부터 왼쪽 자식인지를 기록하면서 순회한다. 부모의 왼쪽 노드이면서 왼쪽, 오른쪽 자식이 없는 잎노드 일 경우 결과에 현재 노드의 value를 더해준다.
'알고리즘' 카테고리의 다른 글
[트리] 1302. Deepest Leaves Sum (가장 깊은 잎들의 합을 구하기) (0) | 2020.06.21 |
---|---|
[트리] 이진 트리의 최대 깊이 (104. Maximum Depth of Binary Tree) (0) | 2020.06.21 |
Longest Palindromic Substring (0) | 2020.06.05 |
longest-substring-without-repeating-characters (0) | 2020.05.30 |
[leetcode] 추천 75문제 중 1번. twoSum (0) | 2019.12.12 |
댓글
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- useRef
- react hooks
- es6
- type alias
- Next.js
- mobx
- computed
- typescript
- return type
- Babel
- props
- hydrate
- server side rendering
- useEffect
- Action
- atomic design
- reducer
- async
- await
- storybook
- reactdom
- webpack
- Polyfill
- react
- javascript
- rendering scope
- promise
- reflow
- design system
- state
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
글 보관함