• 103. Binary Tree Zigzag Level Order Traversal (Tree, Queue; BFS)


    Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

    For example:
    Given binary tree [3,9,20,null,null,15,7],

        3
       /
      9  20
        / 
       15   7

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]
    思路:还是层次遍历,只是增加一个int或bool类型变量标示当前行是否需要reverse。

    /**
     * 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>> zigzagLevelOrder(TreeNode* root) {
            vector<queue<TreeNode*>> q(2);
            int curIndex = 0;
            int nextIndex = 1;
            int levelIndex = 0;
            vector<int> retItem;
            vector<vector<int>> ret;
            
            if(root) q[curIndex].push(root);
            while(!q[curIndex].empty()){
                retItem.push_back(q[curIndex].front()->val);
                if(q[curIndex].front()->left) q[nextIndex].push(q[curIndex].front()->left);
                if(q[curIndex].front()->right) q[nextIndex].push(q[curIndex].front()->right);
                q[curIndex].pop();
                
                if(q[curIndex].empty()){ //end of this level
                    if(levelIndex) reverse(retItem.begin(), retItem.end());
                    ret.push_back(retItem);
                    retItem.clear();
                    curIndex = (curIndex+1) & 0x01;
                    nextIndex = (nextIndex+1) & 0x01;
                    levelIndex = (levelIndex+1) & 0x01;
                }
            }
            
            return ret;
        }
    };
  • 相关阅读:
    时间,关机重启及网络常识
    bash xshell 特性
    Http介绍
    rsync 守护进程模式小记
    定时任务+邮件发送 小记
    4.iptables的匹配条件(一)
    3.iptables规则管理
    2.iptables规则查询
    1.iptables概念
    4.LVS实验构建
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/6067497.html
Copyright © 2020-2023  润新知