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

leetCode(23):Binary Tree Zigzag Level Order Traversal

时间:2015-06-22 11:11:22      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:leetcode   二叉树   

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

又是层序遍历!!!


/**
 * 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) {
        queue<TreeNode*> nodes;
    	vector< vector<int> > result;
    	vector<int> tmp;
    	if(NULL==root)
    		return result;
    	nodes.push(root);
    	bool flag=false;
    	while(!nodes.empty())
    	{
    		int length=nodes.size();
    		int i=0;
    		while(i<length)
    		{
    			TreeNode* tmpNode=nodes.front();
    			tmp.push_back(tmpNode->val);
    			if(tmpNode->left)
    				nodes.push(tmpNode->left);
    			if(tmpNode->right)
    				nodes.push(tmpNode->right);
    			nodes.pop();
    			i++;
    		}
    		if(flag)
    		{
    			reverse(tmp.begin(),tmp.end());
    			flag=false;
    		}
    		else
    		{			
    			flag=true;
    		}
    		result.push_back(tmp);
    		tmp.clear();
    	}
    	return result;
    }
};




leetCode(23):Binary Tree Zigzag Level Order Traversal

标签:leetcode   二叉树   

原文地址:http://blog.csdn.net/walker19900515/article/details/46591677

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