zoukankan      html  css  js  c++  java
  • [LeetCode]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]
    ]
    

    confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

    OJ's Binary Tree Serialization:

    The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

    Here's an example:

       1
      / 
     2   3
        /
       4
        
         5
    

    The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

    思考:偶数层直接反转,竟然过了。

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    private:
    	vector<vector<int> > ret;
    public:
        vector<vector<int> > zigzagLevelOrder(TreeNode *root) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		ret.clear();
    		if(root==NULL) return ret;
    		vector<int> ans;
    		queue<TreeNode *> q;	
    		q.push(root);
    		int num=1;
    		while(!q.empty())
    		{
    			ans.clear();
    			int count=0;
    			while(num--)
    			{			
    				TreeNode *node=q.front();
    				q.pop();
    				ans.push_back(node->val);
    				if(node->left)
    				{
    					count++;
    					q.push(node->left);
    				}
    				if(node->right)
    				{
    					count++;
    					q.push(node->right);
    				}
    			}
    			num=count;
    			ret.push_back(ans);
    		}
    		for(int i=0;i<ret.size();i++)
    		{
    			if(i%2==0) continue;
    			for(int j=0;j<ret[i].size()/2;j++)
    				swap(ret[i][j],ret[i][ret[i].size()-j-1]);
    		}
    		return ret;
    	}
    };
    

      

  • 相关阅读:
    04.DRF-开发REST 接口
    03.DRF-设计方法
    02.DRF-认识RESTful
    01.DRF-Web应用模式
    14.Django-xadmin和富文本编辑器
    13.Django-分页
    12.Django-admin
    11.Django-form表单上传文件
    android 基于wifi模块通信开发
    android蓝牙通讯开发(详细)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3429464.html
Copyright © 2011-2022 走看看