二叉树按层打印

首先以下算法是以宽度优先算法(BFS)为基础,宽度优先搜索是基于队列实现的。

通过设立两个节点变量last(当前打印层的最右节点),nlast(下一打印层的最右节点)来控制换行。

算法流程:

初始化:

last=root (root 是根节点)

循环遍历:

  1. 出队打印
  2. 左右子孩子入队,并赋值nlast
  3. 判断:若出队元素与last相等,则换行,并last=nlast

循环终止条件:

队列为空

C++代码

void linePrint(TreeNode* root) {
        TreeNode* nlast=root;
        TreeNode* last=root;

        queue<TreeNode*> q;
        q.push(root);

        while(!q.empty()) {
            TreeNode* node=q.front();
            q.pop();
            cout<<node->val<<'\t';

            if(node->left!=NULL) {
                q.push(node->left);
                nlast=node->left;
            }

            if(node->right!=NULL) {
                q.push(node->right);
                nlast=node->right;
            }

            if(node==last) {
                last=nlast;
                cout<<"\n";
            }
        }

}

另附

宽度优先搜索(BFS)

可通过队列来实现

void BFS(TreeNode* root)
{
    queue<TreeNode*> q;
    q.push(root);

    while(!q.empty())
    {
        TreeNode* node=q.front();
        cout<<node->val<<'\t';

        if(node->left!=NULL)
            q.push(node->left);
        if(node->right!=NULL)
            q.push(node->right);
        q.pop();

    }

}

深度优先搜索(DFS)

可通过栈来实现

void DFS(TreeNode* root)
{
    stack<TreeNode*> s;
    s.push(root);
    while(!s.empty())
    {
        TreeNode* node=s.top();
        s.pop();
        cout<<node->val<<'\t';
        if(node->right!=NULL)
            s.push(node->right);
        if(node->left!=NULL)
            s.push(node->left);

    }

}

猜你喜欢

转载自blog.csdn.net/czl389/article/details/77781730