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;
        }
        
    };
    
  • 相关阅读:
    【转】Android-Input input&按键布局文件
    【转】Android-Input 触摸设备
    【转】IE沙箱拖拽安全策略解析
    FireFox 插件xpi文件签名2
    如何给Firefox附加组件签名
    【转】用opencv使摄像头在30fps下捕获1080p的数据
    Displaylink安卓驱动
    无主之地2 不费子弹手枪
    jsoncpp
    [APIO2010] 算法竞赛竞赛经典 巡逻
  • 原文地址:https://www.cnblogs.com/ilovezyg/p/7591027.html
Copyright © 2011-2022 走看看