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;
    }
};
posted @ 2017-05-04 17:11  LiBaoquan  阅读(197)  评论(0编辑  收藏  举报