题目描述
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
样例
Input: [8, 12, 2, null, null, 6, null, 4, null, null, null]
Output:[[8], [12, 2], [6], [4]]
解题思路
-
描述
同样是树的层次遍历。
在初始化时,加入root和NULL两个节点。当出队元素为NULL,表明一层结束。
-
实现代码:
vector<vector<int>> printFromTopToBottom(TreeNode* root) { vector<vector<int> > res; // 存放结果 vector<int> cres; // 存放每层元素 if(!root) // 为空,直接返回res { return res; } 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; } res.push_back(cres); // 加入到结果中 cres.clear(); // 清空 q.push(NULL); // 加入NULL,标记下一层的结束 } } return res; }