码迷,mamicode.com
首页 > 其他好文 > 详细

剑指offer 39_二叉树的深度

时间:2015-08-18 13:35:21      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:

 

 

 

#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);
}

 

剑指offer 39_二叉树的深度

标签:

原文地址:http://www.cnblogs.com/maxiaodoubao/p/4738927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!