牛客网 剑指offer 二叉树深度

时间限制:1秒空间限制:32768K热度指数:8903

**算法知识视频讲解

题目描述

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

我觉得给的函数一点都不好。。。咳咳。。。囧。。

代码如下:

/*
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==NULL)return 0;
    	int n=1;
        Depth(pRoot,1,n);
        return n;
    }
    void Depth(TreeNode* pRoot,int depth,int &n)
    {
        if(pRoot==NULL){
            return;
        }
        if(depth>n)n=depth;
        Depth(pRoot->left,depth+1,n);
        Depth(pRoot->right,depth+1,n);   
    }
};

打赏一个呗

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦