首页 > 其他 > 详细

剑指offer:二叉树的深度

时间:2019-03-26 23:45:15      阅读:183      评论:0      收藏:0      [点我收藏+]

题目描述:

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

 

解题思路:

这道题也是递归的思路,比较简单。

做的过程中遇到的一个问题是return count++这句,实际返回的是count之后再加了。还是直接用count+1返回。

 

代码:

/*
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
            val(x), left(NULL), right(NULL) {
    }
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==nullptr)
            return 0;
        int count=0;
        if(pRoot->left==nullptr && pRoot->right==nullptr)
            return count+1;
        count++;
        return count+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
    
    }
};

 

剑指offer:二叉树的深度

原文:https://www.cnblogs.com/LJ-LJ/p/10604521.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!