首页 > 代码库 > 【LeetCode】 Maximum Depth of Binary Tree

【LeetCode】 Maximum Depth of Binary Tree

    题目

    Given a binary tree, find its maximum depth.

    The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.


     思路

    简单递归的考查,求一棵树的深度。只要在左子树和右子树中取最大高度加 1 就是根的高度,递归下去就行。


     代码

/**
 * Definition for binary tree
 * 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;

        int ans = 1;
        int l = maxDepth(root->left);
        int r = maxDepth(root->right);

        ans += max(l,r);

        return ans;
    }
};

【LeetCode】 Maximum Depth of Binary Tree