leetcode-103 100%submissions

第一百零三题:(层次遍历二叉树问题)自己写的

1.边界情况:

根结点为空。

2.思路:

就用一个双端队列(可以从头尾进出),利用变量保存每层的结点个数,每层交替进队和出队规则。

 算法代码

class Solution {
public:
 vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
	 vector<vector<int>> res;
	 if (root == NULL)
		 return res;
	 deque<TreeNode*> Q;
	 Q.push_back(root);
	 int i = 1, j = 0, layer = 0;
	 bool dir = true;
	 res.push_back(vector<int>());
	 while (!Q.empty()){
		 TreeNode* temp;
		 if (dir){
			 temp = Q.front();
			 Q.pop_front();
			 if (temp->left!=NULL){
				 Q.push_back(temp->left);
				 j++;
			 }
			 if (temp->right != NULL){
				 Q.push_back(temp->right);
				 j++;
			 }
		 }
		 else{
			 temp = Q.back();
			 Q.pop_back();
			 if (temp->right != NULL){
				 Q.push_front(temp->right);
				 j++;
			 }
			 if (temp->left != NULL){
				 Q.push_front(temp->left);
				 j++;
			 }
		 }
		 res[layer].push_back(temp->val);
		 i--;
		 if (j != 0 && i == 0){
			 res.push_back(vector<int>());
			 layer++;
			 dir = !dir;
			 i = j;
			 j = 0;
		 }
	 }
	 return res;
 }
};
static const int _ = []() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    return 0;
}();

猜你喜欢

转载自blog.csdn.net/aa568551096/article/details/84563671