• LintCode-71.二叉树的锯齿形层次遍历


    二叉树的锯齿形层次遍历

    给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)

    样例

    给出一棵二叉树 {3,9,20,#,#,15,7},

    返回其锯齿形的层次遍历为:
    [
        [3],
        [20,9],
        [15,7]
    ]

    标签

    领英 二叉树 队列 二叉树遍历 宽度优先搜索

    code

    /**
     * Definition of TreeNode:
     * class TreeNode {
     * public:
     *     int val;
     *     TreeNode *left, *right;
     *     TreeNode(int val) {
     *         this->val = val;
     *         this->left = this->right = NULL;
     *     }
     * }
     */
    class Solution {
        /**
         * @param root: The root of binary tree.
         * @return: A list of lists of integer include 
         *          the zigzag level order traversal of its nodes' values 
         */
    public:
        vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
            // write your code here
            vector<vector<int> > order;
            queue<TreeNode*> queue;
            int len,leaver=1;
    
            if(root == NULL) {
                return order;
            }
    
            queue.push(root);
            len = queue.size();
    
            while(!queue.empty()) {  
                vector<int> base;  
                len = queue.size();
                
                while(len--) {
                    TreeNode *tmp=queue.front();  
                    base.push_back(tmp->val);
                    queue.pop();  
                    if(tmp->right)      
                        queue.push(tmp->right);  
                    if(tmp->left)  
                        queue.push(tmp->left);  
                }
    
                if(leaver%2 == 1)
                    reverse(base.begin(),base.end());
                order.push_back(base); 
                leaver++;
            }  
            return order;
        }
    };
  • 相关阅读:
    CSS学习笔记
    metadata的深入
    [极客大挑战 2019]BabySQL
    [极客大挑战 2019]LoveSQL
    [强网杯 2019]随便注
    [SUCTF 2019]CheckIn 1
    [ZJCTF 2019]NiZhuanSiWei 1
    [BJDCTF2020]Easy MD5
    [极客大挑战 2019]BuyFlag
    [ACTF2020 新生赛]BackupFile
  • 原文地址:https://www.cnblogs.com/libaoquan/p/6808184.html
Copyright © 2020-2023  润新知