二叉树的最大深度

Posted tianzeng

tags:

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

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

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

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

示例:
给定二叉树 [3,9,20,null,null,15,7],

3
/
9 20
/
15 7
返回它的最大深度 3 。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(!root)
            return 0;
        
        int leftDepth=maxDepth(root->left);
        int rightDepth=maxDepth(root->right);
        return max(leftDepth,rightDepth)+1;
    }
};

 

以上是关于二叉树的最大深度的主要内容,如果未能解决你的问题,请参考以下文章

二叉树--二叉树的最大深度

104. 二叉树的最大深度

二叉树的最大深度 递归

LC 二叉树的最大深度

二叉树——高度和深度

求二叉树的最大深度