JZ55 二叉树的深度

二叉树的深度_牛客题霸_牛客网

递归代码太简单-一行就可以,可以用二叉树的层序遍历,顺便温习下二叉树层序遍历的写法。

对应leetcode 104题,层序遍历对应leetcode-102自顶向下,leetcode-107自底向上

/*
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)return 0;
		// int depthLeft = TreeDepth(pRoot->left);
		// int depthRight = TreeDepth(pRoot->right);
		
		// return (depthLeft>depthRight)?(depthLeft+1):(depthRight+1);
		//层次遍历求树的深度
		// return pRoot? 1+max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)): 0;
		//递归一行代码搞定
		if(!pRoot)return 0;
		TreeNode *pCur = pRoot, *plast = pRoot,*prelast = pRoot;
		queue<TreeNode*>treeQueue;
		int level_cnt = 0;
		treeQueue.push(pCur);
		while(!treeQueue.empty()){
			pCur = treeQueue.front();
			if(pCur->left){
				treeQueue.push(pCur->left);
				plast = pCur->left;
			}
			if(pCur->right){
				treeQueue.push(pCur->right);
				plast = pCur->right;
			}
			// treeQueue.pop();
			if(prelast == pCur){ //prelast=pCur的时候,plast始终指向pCur下一层的最右结点
				++level_cnt;
				prelast = plast;//更新prelast
			}
			treeQueue.pop();
		}
		return level_cnt;

    }
};

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

给你。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值