LeetCode题目:Binary Tree Zigzag Level Order Traversal

By | 2012 年 12 月 10 日

比较简单,广度优先变一下就可以了,用一个bool记录是从左到右还是从右到左,每一层结束就翻转一下。



Binary Tree Zigzag Level Order Traversal
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]
]



代码:28ms过大集合

/**
 * 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 > zigzagLevelOrder(TreeNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector > ret;
        if(NULL == root) return ret;
        
        queue que;
        que.push(root);
        que.push(NULL);//level end point
        
        bool l2r = true;//left to right
        
        vector level;
        while(true) {
            TreeNode *cur = que.front();
            que.pop();
            if(cur) {
                level.push_back(cur->val);
                if(cur->left) que.push(cur->left);
                if(cur->right) que.push(cur->right);
            } else {
                if(l2r) {
                    ret.push_back(level);
                } else {
                    vector temp;
                    for(int i = level.size() - 1 ; i >= 0; --i) {
                        temp.push_back(level[i]);
                    }
                    ret.push_back(temp);
                }
                level.erase(level.begin(),level.end());
                l2r = !l2r;
                
                if(que.size() == 0) break;
                que.push(NULL);
            }
        }
        
        return ret;
    }
};

发表评论

电子邮件地址不会被公开。 必填项已用*标注