5.4.1—二叉树的递归—Minimum Depth of Binary Tree

来源:互联网 发布:mmd双人动作数据 编辑:程序博客网 时间:2024/06/05 09:09
描述
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the
nearest leaf node.

#include "BinaryTree.h"#include<vector>using namespace std;//===求一棵二叉树的最小深度int MinDepth(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;if (proot->m_pLeft&&!proot->m_pRight) return 1;return MinDepth(proot->m_pLeft) < MinDepth(proot->m_pRight) ? 1+MinDepth(proot->m_pLeft) : 1+MinDepth(proot->m_pRight);}// ====================测试代码====================//            8//        6      10//       5 7    9  11int 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, pNode10);ConnectTreeNodes(pNode6, pNode5, pNode7);ConnectTreeNodes(pNode10, pNode9, pNode11);//===//PrintTree(pNode8);//===int mindepth = MinDepth(pNode8);cout << mindepth << endl;DestroyTree(pNode8);}



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