本系列文章已全部上傳至我的github,地址:ZeeCoder‘s Github
歡迎大家關(guān)注我的新浪微博,我的新浪微博
歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明出處
來源: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for >the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:[
[3],
[20,9],
[15,7]
]
題目大意:給定1個(gè)2叉樹,按層序遍歷輸出,層數(shù)從1開始,奇數(shù)層從左往右輸出,偶數(shù)層從右往左輸出。
解題思路:上1題【1天1道LeetCode】#102. Binary Tree Level Order Traversal采取queue的數(shù)據(jù)結(jié)構(gòu)來層序輸出,每層都是按從左往右的順序輸出,所以,這1題可以采取deque的數(shù)據(jù)結(jié)構(gòu),根據(jù)奇數(shù)和偶數(shù)層來判斷輸出順序。
詳細(xì)解釋見代碼:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> ret;
if(root==NULL) return ret;
deque<TreeNode*> deq;//用來寄存每層的節(jié)點(diǎn)
deq.push_back(root);//將根節(jié)點(diǎn)放入queue等待處理
int n = 1;//記錄層數(shù)
while(!deq.empty())
{
vector<int> tempnode;
deque<TreeNode*> temp;//寄存下1層的節(jié)點(diǎn)
while(!deq.empty()){
if(n%2==1)//奇數(shù)層
{
TreeNode* tn = deq.front();//從頭開始取節(jié)點(diǎn)
tempnode.push_back(tn->val);
deq.pop_front();
if(tn->left!=NULL) temp.push_back(tn->left);//從左往右放入節(jié)點(diǎn)
if(tn->right!=NULL) temp.push_back(tn->right);
}
else//偶數(shù)層
{
TreeNode* tn = deq.back();//從尾部開始取節(jié)點(diǎn)
tempnode.push_back(tn->val);
deq.pop_back();
if(tn->right!=NULL) temp.push_front(tn->right);//從右往左放入節(jié)點(diǎn)
if(tn->left!=NULL) temp.push_front(tn->left);
}
}
deq = temp;
ret.push_back(tempnode);
n++;//處理下1層
}
return ret;
}
};
下一篇 密碼破解神器-xhydra