zoukankan      html  css  js  c++  java
  • 面试题32_3:之字形打印二叉树

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

    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: ====
    ");
        printf("Actual Result is: 
    ");
        Printf(pNode8);
        printf("
    ");
        return 0;
    }
    
  • 相关阅读:
    搭建kafka高级消费 (high-consumer)php7
    kafka搭建到配置borker集群(项目开发-区块链)
    快速提高谷歌浏览器(Chrome)自带下载器的网速
    利用IO和File类实现拷贝文件目录问题
    随机红包小算法
    二叉树前序中序后序层序遍历问题
    荷兰国旗问题
    二分法查找
    找出数组中最大值and索引
    数组元素反转
  • 原文地址:https://www.cnblogs.com/flyingrun/p/13393079.html
Copyright © 2011-2022 走看看