您的位置:首页 > 其它

5.4.2—二叉树的递归—Maximum Depth of Binary Tree

2017-08-08 23:43 197 查看
描述

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the

farthest leaf node.

#include "BinaryTree.h"
#include<vector>
#include<stack>
using namespace std;
//===求一棵二叉树的最大深度---递归
int MaxDepth(BinaryTreeNode *proot)
{
if (proot == NULL) return 0;
if (!proot->m_pLeft&&!proot->m_pRight) return 1;
if (!proot->m_pLeft&&proot->m_pRight) return 1+MaxDepth(proot->m_pRight);
if (proot->m_pLeft&&!proot->m_pRight) return 1+MaxDepth(proot->m_pLeft);
return MaxDepth(proot->m_pLeft) > MaxDepth(proot->m_pRight) ? 1+MaxDepth(proot->m_pLeft) : 1+MaxDepth(proot->m_pRight);
}

// ====================测试代码====================
//            8
//        6
//      5   7
//   10  11
//  9

int main()
{
//===
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode10 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode11 = CreateBinaryTreeNode(11);

ConnectTreeNodes(pNode8, pNode6, NULL);
ConnectTreeNodes(pNode6, pNode5, pNode7);
ConnectTreeNodes(pNode5, pNode10, pNode11);
ConnectTreeNodes(pNode10, pNode9, NULL);

//===
//PrintTree(pNode8);
//===
int maxdepth = MaxDepth(pNode8);
cout << maxdepth << endl;

//===

DestroyTree(pNode8);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: