题目描述
请实现一个函数按照之字形顺序从上向下打印二叉树。
即第一行按照从左到右的顺序打印,第二层按照从右到左的顺序打印,第三行再按照从左到右的顺序打印,其他行以此类推。
样例
Input: [8, 12, 2, null, null, 6, null, 4, null, null, null]
Output:[[8], [2, 12], [6, 4]]
解题思路
-
描述
同样是树的层次遍历。
在初始化时,加入root和NULL两个节点。当出队元素为NULL,表明一层结束。
根据层数翻转存储每层元素的数组即可。
-
实现代码:
vector<vector<int>> printFromTopToBottom(TreeNode* root) { vector<vector<int> > res; // 存放结果 vector<int> cres; // 存放每层元素 if(!root) // 为空,直接返回res { return res; } bool level = true; queue<TreeNode*> q; TreeNode* tmp; q.push(root); q.push(NULL); while(!q.empty()) { tmp = q.front(); q.pop(); if(tmp) // 出队元素非空,按照层次遍历正常情况处理 { cres.push_back(tmp->val); if(tmp->left) { q.push(tmp->left); } if(tmp->right) { q.push(tmp->right); } } else { if(cres.empty()) // 当该层元素为空,表明树已遍历完成 { break; } if(!level) // level为false { reverse(cres.begin(),cres.end()); } res.push_back(cres); // 加入到结果中 cres.clear(); // 清空 q.push(NULL); // 加入NULL,标记下一层的结束 level = !level; } } return res; }