首页 > 其他 > 详细

leetcode-剑指32-III-OK

时间:2021-02-03 23:19:42      阅读:31      评论:0      收藏:0      [点我收藏+]
// 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<TreeNode*> q;
    	queue<int> mid;
    	TreeNode* temp;
    	q.push(root);
    	int level =0;
    	while(!empty(q)){
    		level++;
    		p.swap(q);
    		vector<int> linshi;
    		while(!empty(p)){
    			temp = p.front();
    			p.pop();
    			if(temp->left !=NULL)
    				q.push(temp->left);
    			if(temp->right !=NULL)
    				q.push(temp->right);
    			linshi.push_back(temp->val);
    		}
    		if(level%2 ==0){
    			while(!empty(linshi)){
    				mid.push(linshi.back());
    				linshi.pop_back();
    			}
    			while(!empty(mid)){
    				linshi.push_back(mid.front());
    				mid.pop();
    			}
    		}
    		ans.push_back(linshi);
    	}
    	return ans;
    }
};

leetcode-剑指32-III-OK

原文:https://www.cnblogs.com/gallien/p/14369730.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!