一棵圣诞树记作根节点为 root 的二叉树,节点值为该位置装饰彩灯的颜色编号。请按照如下规则记录彩灯装饰结果:
第一层按照从左到右的顺序记录
除第一层外每一层的记录顺序均与上一层相反。即第一层为从左到右,第二层为从右到左。
示例 1:
输入:root = [8,17,21,18,null,null,6]
输出:[[8],[21,17],[18,6]]
提示:
节点总数 <= 1000
输入:root = [8,17,21,18,null,null,6]
输出:[[8],[21,17],[18,6]]
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/
class Solution {
public:vector<vector<int>> decorateRecord(TreeNode* root) {deque<TreeNode*> deque;vector<vector<int>> res;if(root != NULL) deque.push_back(root);while(!deque.empty()) {// 打印奇数层vector<int> tmp;for(int i = deque.size(); i > 0; i--) {// 从左向右打印TreeNode* node = deque.front();deque.pop_front();tmp.push_back(node->val);// 先左后右加入下层节点if(node->left != NULL) deque.push_back(node->left);if(node->right != NULL) deque.push_back(node->right);}res.push_back(tmp);if(deque.empty()) break; // 若为空则提前跳出// 打印偶数层tmp.clear();for(int i = deque.size(); i > 0; i--) {// 从右向左打印TreeNode* node = deque.back();deque.pop_back();tmp.push_back(node->val);// 先右后左加入下层节点if(node->right != NULL) deque.push_front(node->right);if(node->left != NULL) deque.push_front(node->left);}res.push_back(tmp);}return res;}
};