《LeetCode之每日一题》:216.二叉树的最大深度

Posted 是七喜呀!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了《LeetCode之每日一题》:216.二叉树的最大深度相关的知识,希望对你有一定的参考价值。

二叉树的最大深度


题目链接: 二叉树的最大深度

有关题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

题解

法一:深度优先搜索(BFS)

/**
 * 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 maxDepth(TreeNode* root) 
        if (root == nullptr)
            return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    
;


法二:广度优先搜索(DFS)
参考官方题解

/**
 * 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 maxDepth(TreeNode* root) 
        if (root == nullptr)
            return 0;
        int ans = 0;
        queue<TreeNode *> q;
        q.push(root);
        while(!q.empty())
        
            int sz = q.size();
            while(sz > 0)
            
                TreeNode* node = q.front(); q.pop();
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
                sz--;
            
            ans++;
        

        return ans;
    
;

以上是关于《LeetCode之每日一题》:216.二叉树的最大深度的主要内容,如果未能解决你的问题,请参考以下文章

《LeetCode之每日一题》:211.二叉树的坡度

LeetCode 993. 二叉树的堂兄弟节点——每日一题

LeetCode 993. 二叉树的堂兄弟节点——每日一题

LeetCode 993. 二叉树的堂兄弟节点——每日一题

leetcode每日一题:(2020-05-10):236.二叉树的最近公共祖先

leetcode每日一题:(2020-05-10):236.二叉树的最近公共祖先