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>> ret;
                
                if (pRoot == NULL) {
                    return ret;
                }
                
                queue<TreeNode*> q;
                q.push(pRoot);
                while (!q.empty()) {
                    int len = q.size();
                    vector<int> tmp(len);
                    for (int i = 0; i < len; ++i) {
                        TreeNode* cur = q.front(); q.pop();
                        tmp[i] = cur->val;
                        if (cur->left) q.push(cur->left);
                        if (cur->right) q.push(cur->right);
                    }
                    ret.push_back(tmp);
                }
                return ret;
            }
    };
    

    之字形打印

    BFS做一下修改。

    /*
    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>> ret;
            
            if (pRoot == NULL) {
                return ret;
            }
            
            vector<TreeNode*> q;
            q.push_back(pRoot);
            bool sign = true;  // sign为true从左到右,否则从右到左
            for (int i = 0; i < q.size(); ) {
                int start = i, end = q.size() - 1;
                vector<int> tmp(end-start+1);
                int k = 0;
                for (int j = start; j <= end; ++j) {
                    tmp[k++] = q[j]->val;
                    if (q[j]->left) q.push_back(q[j]->left);
                    if (q[j]->right) q.push_back(q[j]->right);
                }
                if (!sign) std::reverse(tmp.begin(), tmp.end());
                ret.push_back(tmp);
                i = end + 1;
                sign = !sign;
            }
            return ret;
        }
        
    };
    
  • 相关阅读:
    [数据结构]线性表
    对C语言中指针的一些新认识
    Qt做动画旋转旋转图片
    延时程序执行Qt
    关于部分网页打不可的问题
    关于QString中的arg()函数使用方法
    Qt5.3.0 for Android开发环境配置
    QMenu,contextmenuevent,窗体透明
    Qt自定义窗体,边框,圆角窗体
    一个良好的团队
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/7591027.html
Copyright © 2011-2022 走看看