码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode_104_Maximum Depth of Binary Tree

时间:2015-02-17 10:25:14      阅读:168      评论:0      收藏:0      [点我收藏+]

标签:leetcode   c++   tree   

欢迎大家阅读参考,如有错误或疑问请留言纠正,谢谢技术分享


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)自顶向下逐层累加的,而高度是从叶节点开始(其高度为1)自底向上逐层累加的。


class Solution {
private:
    int depth = 0;
    void maxDepthUtil(TreeNode *root , int d)
    {
        if(root == NULL)
            return;
        if(d > depth)
            depth = d;
        maxDepthUtil( root->left, d+1);
        maxDepthUtil( root->right, d+1);
    }
public:
    int maxDepth(TreeNode *root) {
        maxDepthUtil( root,1 );
        return depth;
    }
};


//另一种写法
class Solution {
public:
    int maxDepth(TreeNode *root) {
        if(root == NULL)
            return 0;
        return max( maxDepth(root->left),maxDepth(root->right) )+1;
    }
};


leetcode_104_Maximum Depth of Binary Tree

标签:leetcode   c++   tree   

原文地址:http://blog.csdn.net/keyyuanxin/article/details/43865255

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!