LeetCode 103. 二叉树的锯齿形层次遍历(BFS / 双栈)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 103. 二叉树的锯齿形层次遍历(BFS / 双栈)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 題目
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如: 給定二叉樹 [3,9,20,null,null,15,7],3/ \9 20/ \15 7 返回鋸齒形層次遍歷如下:[[3],[20,9],[15,7] ]來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
2.1 BFS,隊列,反轉
class Solution { public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {if(root == NULL)return {};queue<TreeNode*> q;TreeNode *tp;q.push(root);vector<int> lv;vector<vector<int>> ans;int n, depth = 0;while(!q.empty()){n = q.size();while(n--){tp = q.front();q.pop();lv.push_back(tp->val); if(tp->left)q.push(tp->left);if(tp->right)q.push(tp->right);}depth++;if(depth%2 == 0)//對相應的層,進行反轉reverse(lv.begin(),lv.end());ans.push_back(lv);lv.clear();}return ans;} };2.2 雙棧解題
- 奇偶層分別存在不同的棧里
- 某個棧里的數據先入棧右節點
2.3 雙端隊列
class Solution { public:vector<vector<int>> zigzagLevelOrder(TreeNode* root) {if(root == NULL)return {};queue<TreeNode*> q;TreeNode *tp;q.push(root);deque<int> lv;vector<vector<int>> ans;int n, depth = 0;while(!q.empty()){n = q.size();while(n--){tp = q.front();q.pop();if(depth%2 == 0)lv.push_back(tp->val);elselv.push_front(tp->val);if(tp->left)q.push(tp->left);if(tp->right)q.push(tp->right);}depth++;ans.push_back(vector<int>(lv.begin(),lv.end()));lv.clear();}return ans;} };總結
以上是生活随笔為你收集整理的LeetCode 103. 二叉树的锯齿形层次遍历(BFS / 双栈)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 泰坦尼克号生存预测入门
- 下一篇: 程序员面试金典 - 面试题 02.05.