Leetcode-104 Maximum Depth of Binary Tree

#104  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.

即给定一颗二叉树,求出其最大深度。

题解:采用深度优先搜索DFS

如果根节点为空,则深度为0,返回0,递归的出口

如果根节点不为空,那么深度至少为1,然后我们求他们左右子树的深度

比较左右子树深度值,返回较大的那一个

通过递归调用

class Solution {
public:
     int max(int a,int b)
    {
        if(a>=b)
        return a;
        else
        return b;
    }
    int maxDepth(TreeNode* root) {
        if(root == NULL)
            return 0;
        return 1 + max(maxDepth(root->left), maxDepth(root->right));
    }
};
原文地址:https://www.cnblogs.com/fengxw/p/6061583.html