码迷,mamicode.com
首页 > 其他好文 > 详细

Binary Tree Zigzag Level Order Traversal -- leetcode

时间:2015-05-06 17:50:43      阅读:111      评论:0      收藏:0      [点我收藏+]

标签: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]
]

基本思路:

1. 使用广度优先搜索

2. 交替使用两个栈。一个表示当前层,一个表示下一层的节点。

3. 使用一个标志变量,表示该层中,先入左节点,还是先入右结点。

在leetcode上实际执行时间为4ms。


/**
 * 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> > ans;
        if (!root) return ans;
        stack<TreeNode *> *next = new stack<TreeNode *>();
        stack<TreeNode *> *curr = new stack<TreeNode *>();
        curr->push(root);
        bool flag = true;
        while (!curr->empty()) {
            ans.push_back(vector<int>());
            ans.back().reserve(curr->size());
            while (!curr->empty()) {
                root = curr->top();
                curr->pop();
                ans.back().push_back(root->val);
                if (flag) {
                    if (root->left) next->push(root->left);
                    if (root->right) next->push(root->right);
                }
                else {
                    if (root->right) next->push(root->right);
                    if (root->left) next->push(root->left);
                }
            }
            swap(next, curr);
            flag = !flag;
        }
        
        delete next;
        delete curr;
        return ans;
    }
};


Binary Tree Zigzag Level Order Traversal -- leetcode

标签:traversal   二叉树   广度优先   

原文地址:http://blog.csdn.net/elton_xiao/article/details/45537385

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!