题目:从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路:定义一个队列,初始时存储树的根结点,之后从队列头取出结点的值,之后将该结点的左右结点(需要判断结点是否存在)放入队列中,循环直至队列为空。
代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| vector<int> PrintFromTopToBottom(TreeNode* root) { queue<TreeNode*> que; vector<int> res; if (root == NULL) return res; que.push(root); while (!que.empty()) { root = que.front(); que.pop(); res.push_back(root->val); if (root->left) que.push(root->left); if (root->right) que.push(root->right); } return res; }
|