103. 二叉树的锯齿形层次遍历
生活随笔
收集整理的這篇文章主要介紹了
103. 二叉树的锯齿形层次遍历
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹?[3,9,20,null,null,15,7],
? ? 3
? ?/ \
? 9 ?20
? ? / ?\
? ?15 ? 7
返回鋸齒形層次遍歷如下:
[
? [3],
? [20,9],
? [15,7]
]
解法:
class Solution { public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {if(!root) return {};vector<vector<int>> res;queue<TreeNode *> qu;qu.push(root);int n = 0;while(!qu.empty()){int count = qu.size();vector<int> curr;while(count--){TreeNode *s = qu.front();qu.pop();curr.push_back(s->val);if(s->left) qu.push(s->left);if(s->right) qu.push(s->right);}++n;if(n % 2 == 0)std::reverse(curr.begin(), curr.end());res.push_back(curr);}return res;} };?
總結
以上是生活随笔為你收集整理的103. 二叉树的锯齿形层次遍历的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无憾青春剧情介绍
- 下一篇: 泰拉瑞亚手游鹿角怪怎么召唤