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

二叉树层次遍历_判断结点所属层次

时间:2018-12-01 15:33:35      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:pac   efi   return   层次遍历   bsp   include   std   http   span   

技术分享图片

技术分享图片

#include<stdlib.h>
#include<stdio.h>
#include<stack>
#define N 50
using namespace std;

typedef struct tree{
    char ch;
    struct tree *lchild;
    struct tree *rchild;
}BitTree; 

//数组输入
BitTree *CreateTree(int A[], int i, int n){
    BitTree *bt;
    if(i>n)
        return NULL;
    else{
        bt=(BitTree *)malloc(sizeof(BitTree));
        if(A[i]==#)
            return NULL;
        bt->ch=A[i];
        bt->lchild=CreateTree(A, 2*i, n);
        bt->rchild=CreateTree(A, 2*i+1, n);
        return bt;
    }
} 

//层次遍历
void LayeredOrderTraverse(BitTree *bt){
    BitTree *QUEUE[N], *p;
    int front, rear;
    if(bt != NULL){
        QUEUE[0] = bt;
        front = 0;
        rear = 1;
        while(front < rear){
            p = QUEUE[front++];
            printf("%c ", p->ch);
            if(p->lchild != NULL)
                QUEUE[rear++] = p->lchild;
            if(p->rchild != NULL)
                QUEUE[rear++] = p->rchild;
        }
    }
}
 
//求结点所在层次
int LayerOrder(BitTree *bt, char c){
    BitTree *STACK1[N], *p = bt;
    int STACK2[N], flag, top = -1;
    while(p != NULL || top != -1){
        while(p != NULL){
            STACK1[++top] = p;
            STACK2[top] = 0;
            p = p->lchild;
        }
        p = STACK1[top];
        flag = STACK2[top--];
        if(flag == 1){
            if(p->ch == c)
                return top+2;
            p = NULL;//容易漏的一步 
        }
        else{
            STACK1[++top] = p;
            STACK2[top] = 1;
            p = p->rchild;
        }
    } 
} 

int main(){
    int A[N]={#,A,B,C,D,E,#,F,G,H};
    BitTree *bt=CreateTree(A,1,9);
    printf("LayeredOrderTraverse:\n");
    LayeredOrderTraverse(bt);
    printf("\n结点A所在层次:\n");
    printf("%d",LayerOrder(bt, A)); 
    printf("\n结点B所在层次:\n");
    printf("%d",LayerOrder(bt, B)); 
    printf("\n结点C所在层次:\n");
    printf("%d",LayerOrder(bt, C)); 
    printf("\n结点D所在层次:\n");
    printf("%d",LayerOrder(bt, D)); 
    printf("\n结点E所在层次:\n");
    printf("%d",LayerOrder(bt, E));
    printf("\n结点F所在层次:\n");
    printf("%d",LayerOrder(bt, F));  
    printf("\n结点G所在层次:\n");
    printf("%d",LayerOrder(bt, G)); 
    printf("\n结点H所在层次:\n");
    printf("%d",LayerOrder(bt, H)); 
    return 0; 
}
/*
输入样例:ABDG##H##E##C#F##
           A
          /          B   C
        / \          D   E   F
      /      G  H
*/

技术分享图片

 

二叉树层次遍历_判断结点所属层次

标签:pac   efi   return   层次遍历   bsp   include   std   http   span   

原文地址:https://www.cnblogs.com/exciting/p/10048957.html

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