leetcode-剑指32-III-OK

// language C with STL(C++)
// 剑指32-III
// https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/


/**
 * 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>> levelOrder(TreeNode* root) {
    	vector<vector<int>> ans;

    	if(root == NULL)
    		return ans;	//空树

    	queue<TreeNode*> p;
    	queue<int> mid;
    	TreeNode* temp;
    	p.push(root);
    	int level =0;
    	int nowsize = 1;
    	int nextsize = 0;
    	while(nowsize!=0){
    		int i =0;
    		level++;
    		vector<int> linshi;
    		while(i<nowsize){
    			temp = p.front();
    			p.pop();
    			if(temp->left !=NULL){
    				p.push(temp->left);
    				nextsize++;
    			}
    			if(temp->right !=NULL){
    				p.push(temp->right);
    				nextsize++;
    			}
    			linshi.push_back(temp->val);
    			i++;
    		}	//本轮填装完毕
    		if(level%2 ==0){
                reverse(linshi.begin(),linshi.end());
    		}
    		ans.push_back(linshi);
    		nowsize = nextsize;
    		nextsize = 0;
    	}
    	return ans;
    }
};
posted @ 2021-02-03 21:05  RougeBW  阅读(30)  评论(0编辑  收藏  举报