二叉树的深度(28)

题目

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


1、分析

  • 二叉树的深度为其左右子树的深度分别加上1(若左右子树存在的话),然后用递归来处理。
    2、代码
/*
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 leftCount = TreeDepth(pRoot->left);
        int rightCount = TreeDepth(pRoot->right);
        return (leftCount>rightCount)?(leftCount+1):(rightCount+1);
    
    }
};
发布了213 篇原创文章 · 获赞 48 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/Jeffxu_lib/article/details/104886084