数据结构与算法——求二叉树的深度

使用递归算法求二叉树的深度

计算二叉树的深度,一般都是用后序遍历,采用递归算法,先计算出左子树的深度,再计算出右子树的深度,最后取较大者加1即为二叉树的深度

struct TreeNode
{
	int data;
	TreeNode* left=nullptr;
	TreeNode* right=nullptr;
};

int TreeDepth(TreeNode* root)
{
	if (!root)
	{
		return 0;
	}
	int left_height = TreeDepth(root->left);
	int right_height = TreeDepth(root->right);
	max = left_height > right_height ? left_height : right_height;
	return max+1;
}

使用非递归算法求二叉树的深度

方式一

定义一个结构体,保存节点信息和其深度,利用DFS的思想,在沿着左子树遍历过程中记录下经过节点的右节点,方便回溯

struct TreeNode
{
	int data;
	TreeNode* left=nullptr;
	TreeNode* right=nullptr;
};

int GetTreeHeight(const TreeNode* root)
{
	struct Info
	{
		const TreeNode* nodeInfo;
		int level;
	};

	deque<Info> dq;
	int level = -1;
	int TreeHeight = -1;
	while (1)
	{
		while (root)
		{
			++level;
			if (root->right)
			{
				Info info;
				info.nodeInfo = root->right;
				info.level = level;
				dq.push_back(info);
			}
			root = root->left;
		}
		
		TreeHeight = max(TreeHeight, level);
		if (dq.empty())
		{
			break;
		}
		const Info& info = dq.back();
		root = info.nodeInfo;
		level = info.level;
		dq.pop_back();
	}
	return TreeHeight;
}

方式二

修改方式一,方式一所用到的辅助栈(双端队列)的大小达到的最大值减去1就等于二叉树的深度。因而只需记录往辅助栈放入元素后(或在访问节点数据时),辅助栈的栈大小达到的最大值

struct TreeNode
{
	int data;
	TreeNode* left=nullptr;
	TreeNode* right=nullptr;
};

int GetTreeHeight(const TreeNode* root)
{
	deque<const TreeNode*> dq;
	int TreeHeight = -1;
	while (1)
	{
		for (; root != nullptr; root = root->left)
		{
			dq.push_back(root);
		}
		TreeHeight = max(TreeHeight, dq.size() - 1);
		while (1)
		{
			if (dq.empty())
			{
				return TreeHeight;
			}
			const TreeNode* parent = dq.back();
			const TreeNode* right = parent->right;
			if (right && root != right)
			{
				root = right;
				break;
			}
			root = parent;
			dq.pop_back();
		}
	}
	return TreeHeight;
}

你可能感兴趣的:(数据结构与算法,数据结构,算法,二叉树,递归)