编程语言
首页 > 编程语言> > JZ55二叉树的深度C++

JZ55二叉树的深度C++

作者:互联网

链接

https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

描述:

在这里插入图片描述

示例:

在这里插入图片描述

代码:

方法一:

class Solution {
public:
	void TreeDepthHelper(TreeNode* pRoot, int curr, int& max) {
		if (pRoot == nullptr) {
			if (max < curr)
				max = curr;
			return;
		}
		TreeDepthHelper(pRoot->left, curr + 1, max);
		TreeDepthHelper(pRoot->right, curr + 1, max);
	}
	int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == nullptr)
			return 0;
		int depth = 0;//遍历到当前位置时,最大的值
		int max = 0;//返回值
		TreeDepthHelper(pRoot, depth, max);
		return max;
	}
};

方法二:

class Solution {
public:
	int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == nullptr) {
			return 0;
		}
		return 1 + max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
		//1+左子树中最大的数字或者右子树最大的数字
	}
};

方法三:

层序遍历,有多少层就是多高

class Solution {
public:
	int TreeDepth(TreeNode* pRoot)
	{
		if (pRoot == nullptr)
			return 0;
		queue<TreeNode*> q;
		q.push(pRoot);
		int depth = 0;
		while (!q.empty()) {
			int size = q.size();
			depth++;
			for (int i = 0; i < size; i++) {
				TreeNode* curr = q.front();
				q.pop(); 
				if (curr->left) q.push(curr->left);
				if (curr->right) q.push(curr->right);
			}
		}
		return depth;
	}
};

标签:curr,int,max,pRoot,C++,TreeNode,二叉树,return,JZ55
来源: https://blog.csdn.net/sakeww/article/details/122814510