二叉树的深度(递归和非递归)

给定一个二叉树,求此二叉树的深度。

递归方法:

int TreeDepth(TreeNode* pRoot)
{
	if (pRoot == NULL)
		return 0;
	if (pRoot->left == NULL && pRoot->right == NULL)
		return 1;
	return max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1;
}
非递归方法:广度遍历思想
int TreeDepth(TreeNode* pRoot)
{
	if (pRoot == NULL)
		return 0;
	queue<TreeNode *> q;
	q.push(pRoot);
	int res = 0;
	while (!q.empty())
	{
		int size = q.size();
		for (int i = 0; i < size; ++i)
		{
			TreeNode *tmp = q.front();
			q.pop();
			if (tmp->left)
			{
				q.push(tmp->left);
			}
			if (tmp->right)
			{
				q.push(tmp->right);
			}
		}
		res++;
	}
	return res;
}

猜你喜欢

转载自blog.csdn.net/yang20141109/article/details/51942473