104. Maximum Depth of Binary Tree

Juhan Kim·2024년 6월 30일

Difficulty Level : Easy

Given the root of a binary tree, return its maximum depth.

A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

 

Example 1:


Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:

Input: root = [1,null,2]
Output: 2
 

Constraints:

The number of nodes in the tree is in the range [0, 104].
-100 <= Node.val <= 100

Solution #1

To know the level of the tree, you have to do the BFS(Breath First Search). Basic Implementation of BFS using two vectors.

/**
 * 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) {}
 * };
 */

#include <vector>

using namespace std;

class Solution {
public:
    int maxDepth(TreeNode* root) {
        vector<TreeNode*> nodes;
        nodes.push_back(root);
        int level = 0; 

        if(root == nullptr){
            return level;
        }

        while(nodes.size() > 0){
            level++;
            vector<TreeNode*> nextLevel;
            while(nodes.size() > 0){
                TreeNode* t = nodes.back();
                nodes.pop_back();
                if(t->left != nullptr){
                    nextLevel.push_back(t->left);
                }
                if(t->right != nullptr){
                    nextLevel.push_back(t->right);
                }
            }
            nodes = nextLevel;
        }

        return level;
    }
};

Solution #2

Amazingly short and beautiful answer. If you see the problem, the problem has to be applied same on the sub problem. So, the solution function can be used recursively.

 #include "MaximumDepthOfBinaryTree.h"

using namespace std;

int Solution::maxDepth(TreeNode* root){
    if (root == nullptr) return 0;
    return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
profile
지식에 대한 열망이 있는 사람

0개의 댓글