1. 程式人生 > >leetcode-103 100%submissions

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;
}();