linus_Robot的博客

渣渣的成长之路

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瞬间解决。

/**
 * 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) {
        int depth=0;
        if (root)
            depth=testMaxDepth(root->left,root->right);
        else
            return 0;
        return depth;
    }
    int testMaxDepth(TreeNode* left,TreeNode* right)
    {
        int depth=1;
        if (left&&right)
            depth+=max(testMaxDepth(left->left,left->right),testMaxDepth(right->left,right->right));
        else if (left) depth+=testMaxDepth(left->left,left->right);
        else if (right) depth+=testMaxDepth(right->left,right->right);
        return depth;
    }
};


阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_26399665/article/details/52372254
个人分类: LeetCode
上一篇103. Binary Tree Zigzag Level Order Traversal
下一篇无法打开包括文件:“SDKDDKVer.h”: No such file or directory
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭