zoukankan      html  css  js  c++  java
  • 按之字形顺序打印二叉树

    题目描述

    请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。

    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int> > ans;
            if (pRoot != NULL) {
            	vector<int> tmp;
                stack<TreeNode*> st;
                stack<TreeNode*> stmp;
                st.push(pRoot);
                TreeNode* cur;
                int tag = 0;
                while (!st.empty()) {
                    while (!st.empty()) {
                        cur = st.top();
                        st.pop();
                        tmp.push_back(cur->val);
                        if (tag == 0) {//从右往左 
                            if (cur->left != NULL) {
                                stmp.push(cur->left);
                            }
                            if (cur->right != NULL) {
                                stmp.push(cur->right);
                            }
                        } else {//从左往右
                            if (cur->right != NULL) {
                                stmp.push(cur->right);
                            }
                            if (cur->left != NULL) {
                                stmp.push(cur->left);
                            }
                        }
                    }
                    tag = 1 - tag;
                    ans.push_back(tmp);
                    tmp.clear();
                    swap(st, stmp);
                }
            }
            return ans;
        }  
        
    };
    
  • 相关阅读:
    Debate
    图形算法
    OpenGL Notes
    How to Write an Ethics Paper
    Thesis
    addWindowListener -> WindowAdapter -> windowClosing
    Thesis
    Bootcamp: An error occurred while partitioning the disk
    What Is XML Schema
    What Is XML
  • 原文地址:https://www.cnblogs.com/jecyhw/p/6652003.html
Copyright © 2011-2022 走看看