牛客题霸 [二叉树的最大深度]C++题解/答案

二叉树的最大深度

题目描述

求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。

题解:

众所周知,树有左子树和右子树,每向下一层,深度就+1,
所以我们就不断递归,看能递归到第几层,答案取最大
详细看代码

代码:

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    int maxDepth(TreeNode* root) {
        // write code here
        if(!root)return 0;
        return max(maxDepth(root->left),maxDepth(root->right))+1;
        
    }
};
posted @ 2020-11-07 00:03  回归梦想  阅读(71)  评论(0编辑  收藏  举报