二叉树的锯齿形层次遍历—leetcode103
生活随笔
收集整理的這篇文章主要介紹了
二叉树的锯齿形层次遍历—leetcode103
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
給定一個二叉樹,返回其節點值的鋸齒形層次遍歷。(即先從左往右,再從右往左進行下一層遍歷,以此類推,層與層之間交替進行)。
例如:
給定二叉樹?[3,9,20,null,null,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;} };?
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的二叉树的锯齿形层次遍历—leetcode103的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 无重复字符的最长子串—leetcode3
- 下一篇: 二叉树的右视图—leetcode199