100-52

本文介绍了一种计算二元树深度的方法。通过递归遍历树的左右子节点,找到最长路径的长度即为树的深度。文章给出了具体的实现代码,并以一个示例二元树为例说明了如何使用该方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

52.二元树的深度(树)。

题目:输入一棵二元树的根结点,求该树的深度。

从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

例如:输入二元树:
                                            10
                                          /     /
                                        6        14
                                      /         /   /
                                    4         12     16

输出该树的深度3。

二元树的结点定义如下:

struct SBinaryTreeNode // a node of the binary tree
{
      int               m_nValue; // value of node
      SBinaryTreeNode  *m_pLeft;  // left child of node
      SBinaryTreeNode  *m_pRight; // right child of node
};
分析:这道题本质上还是考查二元树的遍历。

思路:就像上面说的一样,这道题目其实测试的还是二叉树遍历的操作。最正常的思路就是先序遍历整个树,然后每到一个叶子节点,就记录下当时的深度,并于最大深度进行比较,如果比最大的大,就更新最大记录,这样就能找到树的最大深度。

另外的思路就是采用的递归的方法,要找到一个树的深度,如果根是空的,深度就是0,如果非空,深度就是左子树和右子树中深度比较大的那个加1。这样递归的解决问题。

贴上代码:

//52.二元树的深度(树)。
//题目:输入一棵二元树的根结点,求该树的深度。
//从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
//例如:输入二元树:
//	    10
//	 /     /
//	6      14
//   /      /   /
//  4    12     16
//输出该树的深度3。
//二元树的结点定义如下:
//struct SBinaryTreeNode // a node of the binary tree
//{
//	int               m_nValue; // value of node
//	SBinaryTreeNode  *m_pLeft;  // left child of node
//	SBinaryTreeNode  *m_pRight; // right child of node
//};
//分析:这道题本质上还是考查二元树的遍历。
#include <iostream>

using namespace std;

struct TreeNode 
{
	int value;
	TreeNode *pLeft;
	TreeNode *pRight;
};

void addTreeNode(TreeNode *&pRoot,int *index,int &iCurrent){
	if(-1 != index[iCurrent]){
		TreeNode *pCurrent = new TreeNode;
		pCurrent->value = index[iCurrent++];
		pCurrent->pLeft = NULL;
		pCurrent->pRight = NULL;
		pRoot = pCurrent;

		addTreeNode(pRoot->pLeft,index,iCurrent);
		addTreeNode(pRoot->pRight,index,iCurrent);
	}else{
		++iCurrent;
	}
}

void createTree(TreeNode *&pRoot,int *index){
	int iCurrent = 0;
	addTreeNode(pRoot,index,iCurrent);
}

void inOrder(TreeNode *pRoot){
	if(NULL != pRoot){
		inOrder(pRoot->pLeft);
		cout << pRoot->value << " ";
		inOrder(pRoot->pRight);
	}
}

int treeDepth(TreeNode *pRoot){
	if(NULL == pRoot){
		return 0;
	}else{
		int leftDepth = treeDepth(pRoot->pLeft);
		int rightDepth = treeDepth(pRoot->pRight);
		return (leftDepth > rightDepth ? leftDepth : rightDepth) + 1;
	}
}

int main(){
	int index[] = {10,6,4,-1,-1,-1,14,12,-1,-1,16,-1,-1};//测试数据
	TreeNode *pRoot = NULL;

	createTree(pRoot,index);//创建树
	
	//inOrder(pRoot);

	int ret = treeDepth(pRoot);
	cout << "the depth of the tree is :" << ret << endl;
	
	system("pause");
	return 1;
}

转载于:https://my.oschina.net/dapengking/blog/93501

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值