筆試題:求二叉樹第n層的節點數。

#include <iostream>
#include <string.h>
using namespace std;

template<typename T>
struct Node
{
    T data;
    Node<T> *left;
    Node<T> *right;
    Node(T d = T()) :data(d), left(NULL), right(NULL){}
};
template<typename T>
class MyTree
{
public:
    MyTree() :root(NULL){}
    void Create_Tree(char *LVR,char *LRV)
    {
        int n = strlen(LRV);
        Create_Tree(root,LVR,LRV,n);
    }
    void Printf()
    {
        Printf(root);
    }
    int GetNum(int x)
    {
        int count = 0;//計數。
        x--;
        GetNum(root,count,x);
        return count;
    }
private:
    void GetNum(Node<T> *t, int &count, int x)
    {
        if (t == NULL)return;
        else if (x == 0)
        {
            count++;
            return;
        }
        else
        {
            GetNum(t->left,count,x-1);
            GetNum(t->right, count, x - 1);
        }
    }

    void Printf(Node<T> *t)
    {
        if (t == NULL)return;
        else
        {
            cout << t->data << " ";
            Printf(t->left);
            Printf(t->right);
        }
    }
    void Create_Tree(Node<T> *&t, char *LVR, char *LRV, int len)
    {
        if (len == 0)return;
        int i = 0;
        while (LVR[i] != LRV[len - 1])i++;
        t = new Node<T>(LVR[i]);
        Create_Tree(t->right,LVR+i+1,LRV+i,len-i-1);
        Create_Tree(t->left,LVR,LRV,i);
    }
private:
    Node<T> *root;
};
int main()
{
    MyTree<char> mt;
    char LVR[] = "DCBA";
    char LRV[] = "DCBA";
    mt.Create_Tree(LVR, LRV);
    mt.Printf();
    cout << endl;
    for (int i = 1; i <= 4; i++){
        cout << mt.GetNum(i) << endl;//打印指定層數的節點個數。
    }
    return 0;
}
發佈了291 篇原創文章 · 獲贊 25 · 訪問量 32萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章