leetcode #103 in cpp

来源:互联网 发布:淘宝优惠券小程序 编辑:程序博客网 时间:2024/06/07 19:14

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]]


Solution:

Traverse the tree level by level. Since we want the zig-zag, we change the order of pushing left child and right child. For details please view the code.  

Code:

/** * 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<vector<int>>res;        deque<TreeNode*> nodes;         stack<TreeNode*> stk;        if(!root) return res;        nodes.push_back(root);        bool isl = true;//travel from left to right        while(!nodes.empty()){            vector<int> member;             int cap = nodes.size();             int i = 0;            while(i < cap){                TreeNode *node = nodes.front(); //nodes has been in the order we want, simply push it into member.                member.push_back(node->val);                nodes.pop_front();                if(isl){//the order by which we push left child and right child depends on what direction is it in the next level                    if(node->left) stk.push(node->left);                    if(node->right) stk.push(node->right);                }                else{                    if(node->right) stk.push(node->right);                    if(node->left) stk.push(node->left);                }                i++;            }            while(!stk.empty()){                nodes.push_back(stk.top());                stk.pop();            }            res.push_back(member);            isl = isl?false:true;        }        return res;     }    };


0 0