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

二叉树的建树,按层遍历,结点总数,页结点以及深度

时间:2016-05-16 14:09:37      阅读:113      评论:0      收藏:0      [点我收藏+]

标签:

建立一颗二叉树:

#include "handsomecui.h"
typedef struct Node{
    char data;
    Node *left, *right;
}Node, *Tree;
Tree build(){
    char c;
    SI(c);
    if(c == #){
        return NULL;
    }
    else{
        Node *root = new Node;
        root->data = c;
        root->left = build();
        root->right = build();
        return root;
    }
}
void VisitTree(Node *root){
    if(root == NULL){
        return;
    }
    
    VisitTree(root->left);
    VisitTree(root->right);
    PI(root->data);
}
int main(){
    Tree tree = build();
    VisitTree(tree);
    return 0;
}

按层遍历:

#include "handsomecui.h"
#include<queue>
typedef struct Node{
    char data;
    Node *left, *right;
}Node, *Tree;
Tree build(){
    char c;
    SI(c);
    if(c == #){
        return NULL;
    }
    else{
        Node *root = new Node;
        root->data = c;
        root->left = build();
        root->right = build();
        return root;
    }
}
void Floor_Visit(Node *root){
    queue<Tree>Q;
    Q.push(root);
    while(!Q.empty()){
        root = Q.front();
        Q.pop();
        PI(root->data);
        if(root->left != NULL)
            Q.push(root->left);
        if(root->right != NULL)
            Q.push(root->right); 
    }
}
int main(){
    Tree tree = build();
    PI("按层访问的结果为:\n");
    Floor_Visit(tree);
    return 0;
}

结点总数,页结点以及深度:

#include "handsomecui.h"
typedef struct Node{
    char data;
    Node *left, *right;
}Node, *Tree;
Tree build(){
    char c;
    SI(c);
    if(c == #){
        return NULL;
    }
    else{
        Node *root = new Node;
        root->data = c;
        root->left = build();
        root->right = build();
        return root;
    }
}
int Total_Node(Node *root){
    if(root == NULL)
        return 0;
    else
        return Total_Node(root->left) + Total_Node(root->right) + 1;
}
int Child_Node(Node *root){
    if(root->left == NULL && root->right == NULL){
        return 1;
    }
    else{
        int temp = 0;
        if(root->left != NULL)
            temp += Child_Node(root->left);
        if(root->right != NULL)
            temp += Child_Node(root->right);
        return temp;
    }
}
int Tree_Depth(Node *root){
    if(root == NULL)
        return 0;
    else
        return max(Tree_Depth(root->left), Tree_Depth(root->right)) + 1;
}
int main(){
    Tree tree = build();
    PI("这棵二叉树的总结点为");
    PI(Total_Node(tree)); 
    PI("\n这棵二叉树的页结点为");
    PI(Child_Node(tree)); 
    PI("\n这棵二叉树的深度为");
    PI(Tree_Depth(tree)); 
    return 0;
}

 

二叉树的建树,按层遍历,结点总数,页结点以及深度

标签:

原文地址:http://www.cnblogs.com/handsomecui/p/5497690.html

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