LeetCode 104——二叉树中的最大深度

版权声明:本文为博主原创文章,未经博主允许不得转载 ! https://blog.csdn.net/seniusen/article/details/84259309

1. 题目

2. 解答

如果根节点为空,直接返回 0。如果根节点非空,递归得到其左右子树的深度,树的深度就为左右子树深度的最大值加 1。

/**
 * 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 == NULL) return 0;
        else
        {
            int a = maxDepth(root->left);
            int b = maxDepth(root->right);
            return a > b ? a+1 : b+1;
        }
    }
};

获取更多精彩,请关注「seniusen」!

猜你喜欢

转载自blog.csdn.net/seniusen/article/details/84259309