• 【leetcode】Binary Tree Zigzag Level Order Traversal


    Question :

    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,#,#,15,7},

        3
       / \
      9  20
        /  \
       15   7
    

     

    return its zigzag level order traversal as:

    [
      [3],
      [20,9],
      [15,7]
    ]
    

     

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    Anwser 1 :       

    /**
     * Definition for binary tree
     * 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) {
            // Start typing your C/C++ solution below
            // DO NOT write int main() function
            vector<vector<int>> ret;
            if(root == NULL) return ret;
            
            vector<int> vec;
            stack<TreeNode *> Q;
            stack<TreeNode *> Q2;   // extra space
            bool flag = true;
            
            Q.push(root);
            while(!Q.empty()){
                TreeNode *tmp = Q.top();
                Q.pop();
                
                if(tmp != NULL){
                    vec.push_back(tmp->val);
                    if(flag){
                        if(tmp->left) Q2.push(tmp->left);
                        if(tmp->right) Q2.push(tmp->right);
                    } else {
                        if(tmp->right) Q2.push(tmp->right);
                        if(tmp->left) Q2.push(tmp->left);
                    }
                }
                
                if(Q.empty()){      // one row end
                    ret.push_back(vec);
                    vec.clear();
                    flag = !flag;
                    swap(Q, Q2);
                }
            }
            return ret;
        }
    };


  • 相关阅读:
    vba 填写 Workbok 名片
    VBA 插入和删除工作表
    VBA for each 循环语句
    VBA 中的各种循环
    VBA 的 Join 函数
    VBA 计算数组的最大索引和最小索引
    VBA 变量赋值
    VBA 声明变量
    观察样本的变异程度
    python 将数据写入 Excel 表格
  • 原文地址:https://www.cnblogs.com/xinyuyuanm/p/3032151.html
Copyright © 2020-2023  润新知