二叉樹的鋸齒形層次遍歷—leetcode103
阿新 • • 發佈:2020-12-17
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹[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) { vector<vector<int>> res; if(root==nullptr) return res; stack<TreeNode*> s1,s2; s1.push(root); while(!s1.empty() || !s2.empty()){ vector<int> temp; if(!s1.empty()){ while(!s1.empty()){ TreeNode* node = s1.top(); s1.pop(); if(node->left!=nullptr) s2.push(node->left); if(node->right!=nullptr) s2.push(node->right); temp.push_back(node->val); } }else{ while(!s2.empty()){ TreeNode* node = s2.top(); s2.pop(); if(node->right!=nullptr) s1.push(node->right); if(node->left!=nullptr) s1.push(node->left); temp.push_back(node->val); } } res.push_back(temp); } return res; } };