传送门
nowcoder
leetcode
题目描述
给定一个二叉树,返回该二叉树的之字形层序遍历。
(第一层从左向右,下一层从右向左,一直这样交替)
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: vector<vector<int> > Print(TreeNode* pRoot) { vector<vector<int>> res; if (pRoot == nullptr) return res;
queue<TreeNode*> q; q.push(pRoot); bool isLeft = true; while (!q.empty()) { vector<int> temp; int rowLength = q.size(); while (rowLength --) { TreeNode* node = q.front(); q.pop(); if (node != nullptr) { temp.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } } if (!isLeft) { reverse(temp.begin(), temp.end()); } isLeft = !isLeft; res.push_back(temp); }
return res; } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
class Solution { public: vector<vector<int>> decorateRecord(TreeNode* root) { vector<vector<int>> res; if (!root) return res;
queue<TreeNode*> q; q.push(root); bool isLeft = true; while (!q.empty()) { int n = q.size(); vector<int> level; while (n --) { TreeNode* node = q.front(); q.pop(); level.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } if (!isLeft) reverse(level.begin(), level.end()); isLeft = !isLeft; res.push_back(level); }
return res; } };
class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if (!root) return res;
queue<TreeNode*> q; q.push(root); int cnt = 0; while (!q.empty()) { int n = q.size(); vector<int> level; while (n --) { TreeNode* node = q.front(); q.pop(); level.push_back(node->val); if (node->left) q.push(node->left); if (node->right) q.push(node->right); } if (++ cnt % 2 == 0) { reverse(level.begin(), level.end()); } res.push_back(level); }
return res; } };
|