按照“之”字形输出二叉树

有一颗二叉树如上图,按照“之”字形输出,那么它的输出如下:

测试用例:

功能测试:完全二叉树,只含左孩子的二叉树,只含右孩子的二叉树

特殊值测试:根节点为空,只有一个节点的二叉树

#include<iostream>
#include<string.h>
#include<stack>
#include<vector>

using namespace std;

struct TreeNode{
    int Val;
    TreeNode* LeftNode;
    TreeNode* RightNode;
    TreeNode(int i=0)
    {
        Val=i;
        LeftNode=nullptr;
        RightNode=nullptr;
    }
};

void PrintBinaryTree(TreeNode* root)
{
    if(root==nullptr)return;

    stack<TreeNode*> Outstack[2];
    int current=0;
    int next=1;

    Outstack[0].push(root);
    while(!Outstack[0].empty()||!Outstack[1].empty())
    {
        TreeNode* Node=Outstack[current].top();
        Outstack[current].pop();
        cout<<Node->Val<<' ';

        if(current==0)
        {
            if(Node->LeftNode)
            {
                Outstack[next].push(Node->LeftNode);
            }
            if(Node->RightNode)
            {
                Outstack[next].push(Node->RightNode);
            }
        }
        else
        {
            if(Node->RightNode)
            {
                Outstack[next].push(Node->RightNode);
            }
            if(Node->LeftNode)
            {
                Outstack[next].push(Node->LeftNode);
            }
        }

        if(Outstack[current].empty())
        {
            cout<<endl;
            current=1-current;
            next=1-next;
        }
    }
}

void createtree(TreeNode* &root)
{
    int c;
	cin >> c;
	if ( c == -1 )
		root = nullptr;
	else
	{
		root = new TreeNode(c);
		createtree(root->LeftNode);
		createtree(root->RightNode);
	}
}

int main()
{
    TreeNode* root=nullptr;
    createtree(root);

    PrintBinaryTree(root);
}

在创建二叉树是用的前序的方式创建,当输入 -1 时表示为空节点。

仔细观察输出,发现它的输出满足先进后出,所以可以用栈来保存节点,每次打印当前行的时候,需要保存一下下一行入栈,当左孩子先入栈右孩子后入栈时,是从右向左打印,反之,是从左向右打印。

猜你喜欢

转载自blog.csdn.net/qq_36162275/article/details/87903276