首页 > 其他 > 详细

面试题32_3:之字形打印二叉树

时间:2020-07-28 22:47:10      阅读:92      评论:0      收藏:0      [点我收藏+]

之字形打印二叉树。并非广度优先搜索,需要使用两个辅助栈。

C++版本

#include <iostream>
#include <vector>
#include <stack>
#include <cstring>
#include <queue>
#include <algorithm>
#include "TreeNode.h"
using namespace std;

// 之字形打印二叉树
void Printf(TreeNode* root){
    if(root == nullptr)
        return ;
    // 定义两个辅助栈
    stack<TreeNode*> levels[2];
    // 当前行
    int current = 0;
    int next = 1;

    levels[current].push(root);
    while(!levels[0].empty() || !levels[1].empty()){
        TreeNode* pNode = levels[current].top();
        levels[current].pop();
        cout<<pNode->val<<", ";
        if(current == 0){
            if(pNode->left != nullptr)
                levels[next].push(pNode->left);
            if(pNode->right != nullptr)
                levels[next].push(pNode->right);
        }
        else{
            if(pNode->right != nullptr)
                levels[next].push(pNode->right);
            if(pNode->left != nullptr)
                levels[next].push(pNode->left);
        }
        if(levels[current].empty()){
            cout<<endl;
            current = 1 - current;
            next = 1 - next;
        }
    }
}


int main()
{
    TreeNode* pNode8 = CreateBinaryTreeNode(8);
    TreeNode* pNode6 = CreateBinaryTreeNode(6);
    TreeNode* pNode10 = CreateBinaryTreeNode(10);
    TreeNode* pNode5 = CreateBinaryTreeNode(5);
    TreeNode* pNode7 = CreateBinaryTreeNode(7);
    TreeNode* pNode9 = CreateBinaryTreeNode(9);
    TreeNode* pNode11 = CreateBinaryTreeNode(11);

    ConnectTreeNodes(pNode8, pNode6, pNode10);
    ConnectTreeNodes(pNode6, pNode5, pNode7);
    ConnectTreeNodes(pNode10, pNode9, pNode11);

    printf("====Test1 Begins: ====\n");
    printf("Actual Result is: \n");
    Printf(pNode8);
    printf("\n");
    return 0;
}

面试题32_3:之字形打印二叉树

原文:https://www.cnblogs.com/flyingrun/p/13393079.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!