Count Complete Tree Nodes

ㅋㅋ·2022년 11월 15일
0

알고리즘-leetcode

목록 보기
50/135

완전 이진 트리의 노드수를 구하는 문제

아래의 조건을 만족해야 한다.

Design an algorithm that runs in less than O(n) time complexity.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == NULL)
        {
            return 0;
        }

        return 1 + countNodes(root->left) + countNodes(root->right);
    }
};

0개의 댓글