leetcode 103. 二叉树的锯齿形层次遍历
生活随笔
收集整理的這篇文章主要介紹了
leetcode 103. 二叉树的锯齿形层次遍历
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
給定一個二叉樹,返回其節(jié)點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹?[3,9,20,null,null,15,7],
返回鋸齒形層次遍歷如下:
[[3],[20,9],[15,7] ]?
?
?
1 class Solution { 2 public: 3 vector<vector<int>> zigzagLevelOrder(TreeNode* root) { 4 stack<TreeNode*> s; 5 vector<vector<int>> ans; 6 s.push(root); 7 if(root == NULL) return ans; 8 vector<int> tt; 9 tt.push_back(root->val); 10 ans.push_back(tt); //把第一行加入答案中 11 bool flag = true; 12 while(!s.empty()){ 13 vector<int> t; 14 TreeNode* temp; 15 stack<TreeNode*> st; 16 bool f = false; //標志一次遍歷是否有值壓入 17 18 if(flag){ //從右到左遍歷 19 while(!s.empty()){ 20 temp = s.top(); 21 s.pop(); 22 if(temp->right){ 23 st.push(temp->right); 24 t.push_back(temp->right->val); 25 f = true; 26 } 27 if(temp->left){ 28 st.push(temp->left); 29 t.push_back(temp->left->val); 30 f = true; 31 } 32 } 33 flag = false; 34 s = st; 35 }else{//從左到右遍歷 36 while(!s.empty()){ 37 TreeNode* temp = s.top(); 38 s.pop(); 39 if(temp->left){ 40 st.push(temp->left); 41 t.push_back(temp->left->val); 42 f = true; 43 } 44 if(temp->right){ 45 st.push(temp->right); 46 t.push_back(temp->right->val); 47 f = true; 48 } 49 } 50 flag = true; 51 s = st; 52 } 53 if(f) ans.push_back(t); 54 } 55 return ans; 56 } 57 };?
轉載于:https://www.cnblogs.com/mr-stn/p/8978174.html
總結
以上是生活随笔為你收集整理的leetcode 103. 二叉树的锯齿形层次遍历的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 1.搭建JavaEE开发环境
- 下一篇: PhpStorm 的基本应用