[题目描述]

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.

[解题思路]

又是一道常规的题,求树的深度,本来用非递归的方式要快一些,但是递归的方法确实比较清晰,想法也很简单,从根节点开始,分别求左右子树的深度,然后比较返回较大的深度。


/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (!root)
            return 0;
        int nLeftDeep = 1;
        int nRightDeep = 1;
        if (root->left)
            nLeftDeep = nLeftDeep + maxDepth(root->left);
        if (root->right)
            nRightDeep = nRightDeep + maxDepth(root->right);
        if (nLeftDeep > nRightDeep)
            return nLeftDeep;
        else
            return nRightDeep;
    }
};


[源代码]

https://github.com/rangercyh/leetcode/blob/master/Maximum%20Depth%20of%20Binary%20Tree