剑指offer:二叉树的深度

题目描述:

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

 

解题思路:

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

做的过程中遇到的一个问题是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));
    
    }
};

 

posted @ 2019-03-26 22:59  Fzu_LJ  阅读(78)  评论(0编辑  收藏  举报