求一个简单的二叉树的深度

#include"stdafx.h"
#include<iostream>


using namespace std;


struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;


};


//创建二叉树结点
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
pNode->m_pLeft = NULL;
pNode->m_pRight = NULL;
return pNode;
}


//链接二叉树结点
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if (pParent != NULL)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;


}
}


//求二叉树深度
int TreeDepth(BinaryTreeNode* pRoot)//计算二叉树深度
{
if (pRoot == NULL)//如果pRoot为NULL,则深度为0,这也是递归的返回条件
return 0;
//如果pRoot不为NULL,那么深度至少为1,所以left和right=1
int left = 1;
int right = 1;
left += TreeDepth(pRoot->m_pLeft);//求出左子树的深度
right += TreeDepth(pRoot->m_pRight);//求出右子树的深度


return left > right ? left : right;//返回深度较大的哪一个


}






int main()
{
//                      1
//                   /      \
//                  2         3
//                /   \        \
//               4     5         6
//                   /7
//创建树节点
BinaryTreeNode* pNode1 = CreateBinaryTreeNode(1);
BinaryTreeNode* pNode2 = CreateBinaryTreeNode(2);
BinaryTreeNode* pNode3 = CreateBinaryTreeNode(3);
BinaryTreeNode* pNode4 = CreateBinaryTreeNode(4);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);


//链接树节点
ConnectTreeNodes(pNode1, pNode2, pNode3);
ConnectTreeNodes(pNode2, pNode4, pNode5);
ConnectTreeNodes(pNode3, NULL, pNode6);
ConnectTreeNodes(pNode5, pNode7, NULL);

int depth = TreeDepth(pNode1);
cout << depth << endl;


system("pause");


return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值