二叉樹的層序遍歷

思路:
使用隊列實現二叉樹的層序遍歷,先把root節點入隊,然後每次從隊列刪除一個節點,都訪問此節點,並把節點的左右子節點入隊,直至隊列爲空。層序遍歷結束。

代碼:

#include <iostream>
#include<vector>
#include<queue>

using namespace std;

struct Node{
    int value;
    Node *right;
    Node *left;

    Node()
    {
        value=0;
        right=nullptr;
        left=nullptr;
    }

    Node(int val)
    {
        value=val;
        right=nullptr;
        left=nullptr;
    }

    Node& operator=(const Node& a)
    {
        this->left=a.left;
        this->right=a.right;
        this->value=a.value;
        return *this;
    }
};

class BinTree{

private:
    Node *root;

public:
    BinTree(int value)
    {
        root=new Node(value);
    }

    ~BinTree()
    {
        delete root;
        root=nullptr;
    }

    Node* get_root()
    {
        return root;
    }

    //用隊列實現層序遍歷,傳入遍歷開始節點;注意傳入若爲二叉樹某一子樹的根,則只會遍歷到此子樹。
    void ceng_xu_bianli(Node *start)
    {
        queue<Node*> s;
        s.push(start);
        Node *temp;
        while(!s.empty())
        {
            temp=s.front();
            s.pop();
            cout<<temp->value<<endl;
            if(temp->left!=nullptr)
                s.push(temp->left);
            if(temp->right!=nullptr)
                s.push(temp->right);
        }
        cout<<"層序遍歷結束!"<<endl;
    }

    //注意parent必須是指針的引用;若爲普通指針變量,則以下父子節點鏈接時鏈接到的是臨時指針變量,在函數調用結束即銷燬了。
    Node* Add_Node(int value,Node* &parent,int direction)
    {
        if(direction==1)   //left
        {
            if(parent->left==nullptr)
            {
                Node *new_node=new Node(value);
                parent->left=new_node;
                return new_node;
            }
            else
                cout<<"This node has left child, please choose another node!"<<endl;
        }
        else               //right
        {
            if(parent->right==nullptr)
            {
                Node *new_node=new Node(value);
                parent->right=new_node;
                return new_node;
            }
            else
                cout<<"This node has right child, please choose another node!"<<endl;
        }
        return nullptr;
    }
};

int main()
{
    Node *root;
    BinTree bt(0);
    root=bt.get_root();
    Node *node1=bt.Add_Node(1,root,1);
    Node *node2=bt.Add_Node(2,root,0);
    Node *node3=bt.Add_Node(3,node1,1);
    Node *node8=bt.Add_Node(4,node1,0);
    Node *node4=bt.Add_Node(5,node2,1);
    Node *node5=bt.Add_Node(6,node2,0);
    Node *node6=bt.Add_Node(7,node3,1);
    Node *node7=bt.Add_Node(8,node3,0);

    bt.ceng_xu_bianli(root);
    return 0;
}

輸出:

0
1
2
3
4
5
6
7
8
層序遍歷結束!

Process returned 0 (0x0)   execution time : 0.138 s
Press any key to continue.
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章