leetcode-剑指32-II

// language C with STL(C++)
// 剑指32-II
// https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-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*> q1,q2;
    	q2.push(root);
    	int level = 1;
    	while(!empty(q2)){
    		vector<int> niude;
    		while(!empty(q2)){	// 把q2中的元素移到q1中
    			q1.push(q2.front());
    			q2.pop();
    		}
    		//然后处理q1中的元素
    		TreeNode* temp;
    		while(!empty(q1)){
    			temp = q1.front();
    			q1.pop();
    			niude.push_back(temp->val);
    			if(temp->left)
    				q2.push(temp->left);
    			if(temp->right)
    				q2.push(temp->right);
    		}
    		ans.push_back(niude);
    	}
    	return ans;
    }
};
posted @ 2021-02-02 14:26  RougeBW  阅读(26)  评论(0编辑  收藏  举报