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

LeetCode :: Binary Tree Zigzag Level Order Traversal [tree, BFS]

时间:2014-07-20 22:41:23      阅读:303      评论:0      收藏:0      [点我收藏+]

标签:leetcode   数据结构   tree   bfs   

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

题目的意思很直白,层序遍历整个树,但是第一层正序输出,第二层反序输出,第三层正序输出,以此类推。做法有两种:一、仍然采用level-travel,只是引入一个标记,判断是否反转得到的数列; 二、考虑到stack的特点,利用stack FILO的特点来直接输出;两种方法都贴出来

利用stack的:

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        bool isRe = false;
        vector<int> a;
        stack<TreeNode *> s1, s2;
        
        if (root == NULL)
            return ret;
        s1.push(root);
        while (!s1.empty()){
                TreeNode *tmp = s1.top();
                s1.pop();
                a.push_back(tmp->val);
                    
				if (isRe){
					if (tmp->right)
						s2.push(tmp->right);
					if (tmp->left)
						s2.push(tmp->left);
						}
				else{
					if (tmp->left)
						s2.push(tmp->left);
					if (tmp->right)
						s2.push(tmp->right);
					}
                if (s1.empty()){
                    ret.push_back(a);
                    isRe = !isRe;
					swap(s1, s2);
                    a.clear();
					}
                }
        return ret;
    }
private:
    vector<vector<int>> ret;
};


利用queue的,这里由于引入了swap,所以可以复用同一个代码流程,代码会短一些;

class Solution {
public:
    vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
        vector<vector<int>> ret;
        queue<TreeNode *> current, next;   //利用两个队列的交替来区分每一层
        bool isRe = false;
        vector<int> v;
        
        if (root == NULL)
            return ret;
        current.push(root);
        while (!current.empty()){
            TreeNode *tmp = current.front();
            current.pop();
            v.push_back(tmp->val);
            
            if (tmp->left)
                next.push(tmp->left);
            if (tmp->right)
                next.push(tmp->right);
                
            if(current.empty()){
                if (isRe){
                    reverse(v.begin(), v.end());
                }
                ret.push_back(v);
                swap(current,next);
                isRe = !isRe;
                v.clear();
            }
        }
        
    }
};


LeetCode :: Binary Tree Zigzag Level Order Traversal [tree, BFS]

标签:leetcode   数据结构   tree   bfs   

原文地址:http://blog.csdn.net/u013195320/article/details/37994615

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