zoukankan      html  css  js  c++  java
  • Binary Tree Zigzag Level Order Traversal

    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]
    ]
    BFS,宽度查找法。把同一级别的宽度记下来。訪问的同一时候把下一层弄到队列里面去。经常使用遍历方法!

    class Solution {
    public:
      vector<vector<int>> zigzagLevelOrder(TreeNode* root) 
    	{
    		vector<vector<int>> levelOrderStore;
    		if (root==NULL)
    			return levelOrderStore;
    		queue<TreeNode *>q;
    		stack<TreeNode *>rightout;
    		q.push(root);
    		rightout.push(root);
    		int count=1;
    		int level=0;
    		vector<int> tmp(0);
    		int flag=0;//begin  right->left->right
    		while (!q.empty())//q.root
    		{
    			tmp.clear();
    			level=0;
    			for (int i=0;i<count;i++)//level
    			{
    
    				root=q.front(); //every root.
    				q.pop();
    			
    				if (flag%2==0)
    				{
    					tmp.push_back(root->val);
    				}
    				else
    				{
    					tmp.push_back(rightout.top()->val); //every root.
    						rightout.pop();//
    				}
    			
    				if (root->left!=NULL)
    				{
    					q.push(root->left);
    					if (flag%2==0)
    					{
    						rightout.push(root->left); //
    					}
    					++level;
    				}
    				if (root->right!=NULL)
    				{
    					q.push(root->right);
    					if (flag%2==0)
    					rightout.push(root->right);
    					++level;
    				}
    			}
    			count=level;
    			levelOrderStore.push_back(tmp);
    			flag++;
    		}
    
    		return levelOrderStore;
    	}
    
    };


  • 相关阅读:
    HDU 3555 Bomb (数位DP)
    ms sqlserver数据库主文件特别大怎么办
    w3wp.exe占用cpu特别高
    Excel的数据批量替换
    用Excel的分列功能格式化时间
    sql cte的使用
    数据结构
    http与浏览器学习
    长方形裁切优化与矩形物料排料
    架构知识
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/6847188.html
Copyright © 2011-2022 走看看