生成N个二进制位的组合

#include "stdafx.h"

#include "stdlib.h"
#include "stdio.h"
#include <iostream>
#include <Windows.h>

#define MaxSize 1000

using namespace std;

typedef struct node
{
    int num;
    node * lchild;
    node * rchild;
};

struct chain
{
    node * Node;
    chain * next;
}*head;

typedef struct Stack
{
    int data[MaxSize];
    int top;
};

void postOrder(node *T,Stack s){
    if(T != NULL)
    {
        s.top++;
        s.data[s.top] = T->num;

        if(T->lchild == NULL && T->rchild == NULL){
            for(int i = s.top; i > 0; i--){
                cout << s.data[i];
            }
            cout << endl;
        }

        postOrder(T->lchild,s);
        postOrder(T->rchild,s);

    }
}

//每次新添加的节点加入链表尾部。
void AddNode(int Num)
{

    node * NewNode = (node*)calloc(1,sizeof (node));
    NewNode->num = Num;

    node * FatherNode = head->Node;

    if(FatherNode->lchild == NULL)
        FatherNode->lchild = NewNode;

    else if(FatherNode->rchild == NULL)
    {
        FatherNode->rchild = NewNode;
        //如果右节点也添加了,则链表头移到下一个
        head = head->next ;
    }
    else
        return;

    chain *tail = head;
    //找到链表尾
    while (tail->next != NULL)
        tail = tail->next;

    //添加新节点到链表尾
    chain *Newtail = (chain*)calloc(1,sizeof (chain));
    Newtail->Node = NewNode;
    tail->next = Newtail;
}

int main()
{
    //根节点
    int k = 0; // k层
    node * root=(node*)calloc(1,sizeof (node));
    root->num=1;

    head=(chain*)calloc(1,sizeof (chain));
    head->Node =root;
    head->next =NULL;

    cout << "请输入N(N个二进制位,取值范围大于等于1):" << endl;
    cin >> k;

    k = pow(2.0,k + 1) - 1;

    for(int N = 2;N <= k;N++){
        int tmp = N % 2;
        AddNode(tmp);
    }
    Stack s;
    s.top = -1;

    postOrder(root,s);

    system("pause");

    return 0;
}

参考:http://www.oschina.net/code/snippet_217193_12485

算法分为两个部分。第一,利用二叉树存储01值,在这部分中最重要的一点是利用了一个单链表保存树的每个节点。第二,就是利用栈作为组合的显示输出(其实是反方向输出,先进先显示)。

参考资料中的二叉树的生成方法不仅仅是满二叉树的生成方法。正如他说是按层生成树,我感觉不一定要是满二叉树。不过我的问题结构就是满二叉树。

原文地址:https://www.cnblogs.com/Key-Ky/p/3428037.html