#include <stdio.h> #include <malloc.h> typedef int Item; typedef struct node{ Item m_value; struct node* m_pLeft; struct node* m_pRight; }BinaryTreeNode; int getTreeDepth(BinaryTreeNode *root){ if(root == NULL){ return 0; } int depthLeft = getTreeDepth(root->m_pLeft); int depthRight = getTreeDepth(root->m_pRight); return (depthLeft > depthRight) ? depthLeft + 1 : depthRight + 1; } void PrePrintTree(BinaryTreeNode* root){ if(root != NULL){ printf("%d ",root->m_value); }else{ return; } PrePrintTree(root->m_pLeft); PrePrintTree(root->m_pRight); printf("\n"); } int main(){ BinaryTreeNode* root = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode* node2 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode* node3 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); root->m_pLeft = node2; root->m_pRight = node3; BinaryTreeNode *node4 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode *node5 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode *node6 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); node2->m_pLeft = node4; node2->m_pRight = node5; node3->m_pRight = node6; BinaryTreeNode *node7 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); node5->m_pLeft = node7; BinaryTreeNode *node8 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode *node9 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); node7->m_pLeft = node8; node7->m_pRight = node9; BinaryTreeNode *node10 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); BinaryTreeNode *node11 = (BinaryTreeNode*)malloc(sizeof(BinaryTreeNode)); node9->m_pLeft = node10; node10->m_pLeft = node11; root->m_value = 1; node2->m_value = 2; node3->m_value = 3; node4->m_value = 4; node5->m_value = 5; node6->m_value = 6; node7->m_value = 7; node8->m_value = 8; node9->m_value = 9; node10->m_value = 10; node11->m_value = 11; printf("%d\n\n",getTreeDepth(root)); PrePrintTree(root); }
时间: 2024-10-18 21:53:09