티스토리 뷰
Algorithm/LeetCode
[LeetCode - Daily Challenge] 222.Count Complete Tree Nodes
Jaime.Lee 2021. 10. 25. 09:47Problem
Given the root of a complete binary tree, return the number of the nodes in the tree.
According to Wikipedia, every level, except possibly the last, is completely filled in a complete binary tree, and all nodes in the last level are as far left as possible. It can have between 1 and 2h nodes inclusive at the last level h.
Design an algorithm that runs in less than O(n) time complexity.
Example 1:
Input: root = [1,2,3,4,5,6]
Output: 6
Example 2:
Input: root = []
Output: 0
Example 3:
Input: root = [1]
Output: 1
Constraints:
^ The number of nodes in the tree is in the range [0, 5 * 104].
^ 0 <= Node.val <= 5 * 10^4
^ The tree is guaranteed to be complete.
Solution
완전 이진트리가 주어졌을 때 전체 노드의 갯수를 세는 문제입니다.
Medium 난이도지만 너무 쉬워서 당황스러운 문제입니다.
recursive call을 이용해 풀 수 있습니다.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int countNodes(TreeNode root) {
if(root == null) {
return 0;
}
return 1 + countNodes(root.left) + countNodes(root.right);
}
}
Test
package io.lcalmsky.leetcode.count_complete_tree_nodes;
import io.lcalmsky.leetcode.TreeNode;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
class SolutionTest {
@Test
void givenCompleteTree_whenCount_thenCorrect() {
assertAll(
() -> test(TreeNode.of(1, 2, 3, 4, 5, 6), 6)
);
}
private void test(TreeNode given, int expected) {
// when
Solution countCompleteTreeNodes = new Solution();
int actual = countCompleteTreeNodes.countNodes(given);
// then
assertEquals(expected, actual);
}
}
'Algorithm > LeetCode' 카테고리의 다른 글
[LeetCode - Daily Challenge] 15. 3Sum (0) | 2021.10.29 |
---|---|
[LeetCode - Daily Challenge] 226. Invert Binary Tree (0) | 2021.10.26 |
[LeetCode - Daily Challenge] 496. Next Greater Element I (0) | 2021.10.21 |
[LeetCode - Daily Challenge] 993. Cousins in Binary Tree (0) | 2021.10.20 |
[LeetCode - Daily Challenge] 309. Best Time to Buy and Sell Stock with Cooldown (0) | 2021.10.18 |
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- @ManyToOne
- 스프링 부트 회원 가입
- 클린 아키텍처
- 스프링 부트
- 함께 자라기
- 스프링 데이터 jpa
- Spring Boot
- 알고리즘
- gRPC
- r
- Java
- JPA
- spring boot app
- intellij
- 헥사고날 아키텍처
- JSON
- proto3
- Jackson
- leetcode
- Spring Boot Tutorial
- Spring Boot JPA
- Spring Data JPA
- spring boot jwt
- QueryDSL
- 스프링 부트 애플리케이션
- 함께 자라기 후기
- 스프링 부트 튜토리얼
- 스프링부트
- Linux
- spring boot application
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함