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

来源:互联网 发布:mmd双人动作数据 编辑:程序博客网 时间:2024/05/29 18:50
描述
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//  9int 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);}

阅读全文
0 0
原创粉丝点击