• leetCode(23):Binary Tree Zigzag Level Order Traversal 分类: leetCode 2015-06-22 10:08 127人阅读 评论(0) 收藏


    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;
        }
    };




  • 相关阅读:
    二进制安装postgresql
    php mongodb扩展安装
    coinbase交易冻结时间
    linux服务器及工具常用命令
    PM2下使用 执行npm命令
    phpstorm安装PHP_CodeSniffer
    TP5 save遍历更新,过滤相邻重复字段,问题汇总
    mysqlbinlog 数据恢复
    设计模式之状态机模式
    关于c++中sleep_for函数的总结分析
  • 原文地址:https://www.cnblogs.com/zclzqbx/p/4687092.html
Copyright © 2020-2023  润新知