104. 二叉树的最大深度

问题描述

给定一个二叉树 root ,返回其最大深度。
二叉树的最大深度是指从根节点到最远叶子节点的最长路径上的节点数。

可以使用dfs和bfs两种方法针对树的层数进行遍历,并记录。

递归方法

可以用递归解决,比较简单,用递归函数的返回值承载答案,x表示从当前层到最深层的深度。

class Solution {
public:
    int solve(TreeNode* root) {
        int x = 0;
        if (root == nullptr) {
            return x;
        }
        x++;
        int l_deep = solve(root->left)+x;
        int r_deep = solve(root->right)+x;
        return max(l_deep, r_deep);
    }
    int maxDepth(TreeNode* root) {
        int res = solve(root);
        return res;
    }
};

bfs方法

重点是使用队列时,要判断到哪个结点是树一个层的结束,从而使得层数+1。

可以根据队列中结点数量,使用for循环控制。

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int res = 0;
        queue<TreeNode*> q;
        if (root != nullptr) {
            q.push(root);
        }
        while(!q.empty()) {
            int layer_size = q.size();
            res++;
            for (int i = 0; i < layer_size; i++) {
                TreeNode* t = q.front();
                q.pop();
                if (t->left != nullptr) {q.push(t->left);}
                if (t->right != nullptr) {q.push(t->right);}
            }
        }
        return res;
    }
};

new

层序遍历稍微改一下就行。

/**
 * 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 {
private:
    queue<TreeNode*> q;
    int res = 0;
public:
    int maxDepth(TreeNode* root) {
        if(!root) {return 0;}
        q.push(root);
        while(!q.empty()) {
            int layer_size = q.size();
            for (int i = 0; i < layer_size; i++) {
                TreeNode* t = q.front();
                q.pop();
                if (t->left) {q.push(t->left);}
                if (t->right) {q.push(t->right);}
            }
            res++;
        }
        return res;
    }
};
posted @ 2024-11-25 22:56  saulstavo  阅读(82)  评论(0)    收藏  举报