【剑指offer】【树】32-III. 从上到下打印二叉树

题目链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/

BFS

使用双端队列,始终维持一头进一头出的状态,不然就乱了;

  1. 用res的大小来标志奇偶行;
  2. 偶数行,从左到右,前取后放
  3. 奇数行,从右到左,后取前放
    时间复杂度:O(N)
    空间复杂度:O(N)
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root) return {};
        vector<vector<int>> res;
        deque<TreeNode *> q;
        q.push_back(root);
        while(!q.empty())
        {
            int n = q.size();
            vector<int> line;
            for(int i = 0; i < n; i++)
            {
                //使用res的大小来判断奇偶行
                if(res.size() & 1)  //从右到左 后取前放
                {
                    auto tmp = q.back();
                    q.pop_back();
                    line.push_back(tmp -> val);
                    if(tmp -> right) q.push_front(tmp -> right);
                    if(tmp -> left) q.push_front(tmp -> left);
                }
                else //从左到右 前取后放
                {
                    auto tmp = q.front();
                    q.pop_front();
                    line.push_back(tmp -> val);                    
                    if(tmp -> left) q.push_back(tmp -> left);
                    if(tmp -> right) q.push_back(tmp -> right);
                }
            }
            res.push_back(line);
        }
        return res;
    }
};

posted @ 2020-04-09 21:52  NaughtyCoder  阅读(83)  评论(0)    收藏  举报