题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路:
刚开始看到这题愣了半天,本题实际上就是二叉树的层次遍历,深度遍历可以用递归或者栈,而层次遍历很明显应该使用队列。每次打印一个结点时,如果该结点有子结点,则将子结点放到队列的末尾,接下来取出队列的头重复前面的打印动作,直到队列中所有的结点都打印完毕。
python
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# 返回从上到下每个节点值列表,例:[1,2,3]
def PrintFromTopToBottom(self, root):
# write code here
res = []
if not root :
return []
q = [root]
while len(q):
t = q.pop(0)
res.append(t.val)
if t.left:
q.append(t.left)
if t.right:
q.append(t.right)
return res
c++
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
};*/
#include<queue>
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*> q;
vector<int> v;
if(root == NULL)
return v;
q.push(root);
while(!q.empty())
{root = q.front();
q.pop();
v.push_back(root->val);
if(root->left)
q.push(root->left);
if(root->right)
q.push(root->right);
}
return v;
}
};