1. 程式人生 > 實用技巧 >leetcode103——二叉樹的鋸齒形層次遍歷

leetcode103——二叉樹的鋸齒形層次遍歷

 1 /*
 2  * @lc app=leetcode.cn id=103 lang=cpp
 3  *
 4  * [103] 二叉樹的鋸齒形層次遍歷
 5  */
 6 
 7 // @lc code=start
 8 /**
 9  * Definition for a binary tree node.
10  * struct TreeNode {
11  *     int val;
12  *     TreeNode *left;
13  *     TreeNode *right;
14  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
15 * }; 16 */ 17 class Solution { 18 public: 19 //交替行的輸出,考慮用一個flag標誌位 20 21 /*利用二叉樹的層序遍歷,然後用一個變數來記錄樹的深度(0、1、2...), 22 深度為偶數,從左向右新增這層的節點值;深度為奇數,從右向左新增這層的節點值。*/ 23 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 24 if(!root) return {}; //vector為空時的返回值 25 vector<vector<int
>> res; 26 queue<TreeNode*> q; 27 int flag=0; // 標誌位,判斷哪一行翻轉 28 q.push(root); 29 30 while(!q.empty()){ 31 vector<int> tmp; 32 int len=q.size(); 33 for(int i=0;i<len;i++){ 34 TreeNode* node=q.front();
35 q.pop(); 36 tmp.push_back(node->val); 37 if(node->left) q.push(node->left); 38 if(node->right) q.push(node->right); 39 } 40 if(flag%2==1) reverse(tmp.begin(),tmp.end()); 41 flag++; 42 res.push_back(tmp); 43 } 44 return res; 45 } 46 }; 47 // @lc code=end