计算二叉树的深度

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

分析:

/*

 * 思路1:算出所有路径的深度,然后找出最长的路径,即为深度;  (这种方法代码量比较大)
 * 思路2: 递归思想,如果左右子树都为空,则深度为1;如果左右子树都不为空,则深度为左右子树最大值加1

 *                 如果左子树为空,则深度为右子树深度加1,如果右子树为空,则深度为左子树深度加1;

 * */


代码实现:

int depth_of_binary_tree(t_binarytree_node *p_root)
{
	if (p_root == NULL)
		return 0;

	int left = depth_of_binary_tree(p_root->left);
	int right = depth_of_binary_tree(p_root->right);

	return 1 + (left > right ? left : right);
}



测试case:

	/* 功能测试1 */
	int preorder[] = {1,2,4,7,3,5,6,8};
	int inorder[] = {4,7,2,1,5,3,8,6};

	t_binarytree_node *p_root = NULL;
	p_root = build_binarytree(preorder, inorder, sizeof(preorder)/sizeof(int));
	print_binarytree_by_preorder(p_root);

	cout << "The depth of binary tree is " << depth_of_binary_tree(p_root) << endl;

	/* 异常测试 */
	cout << "The depth of binary tree is " << depth_of_binary_tree(NULL) << endl;

	/* 边界测试1 */
	int preorder2[] = {1};
	int inorder2[] = {1};

	t_binarytree_node *p_root2 = NULL;
	p_root2 = build_binarytree(preorder2, inorder2, sizeof(preorder2)/sizeof(int));
	print_binarytree_by_preorder(p_root2);

	cout << "The depth of binary tree is " << depth_of_binary_tree(p_root2) << endl;

	/* 边界测试2 */
	int preorder3[] = {1,2,4,7};
	int inorder3[] = {4,7,2,1};

	t_binarytree_node *p_root3 = NULL;
	p_root3 = build_binarytree(preorder3, inorder3, sizeof(preorder3)/sizeof(int));
	print_binarytree_by_preorder(p_root3);

	cout << "The depth of binary tree is " << depth_of_binary_tree(p_root3) << endl;



考点总结:

递归思想

知识迁移能力:题目是做不完的,要去分析解题的思路,然后将这些思路应用到其他的场景;



参考文献:

http://zhedahht.blog.163.com/blog/static/25411174200732975328975/  



你可能感兴趣的:(数据结构与算法)