题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
分析:
同层从左至右打印,可以用队列来依次保存每一层的每个节点,并将该结点的值存入数组中;若该结点的左节点或右结点不为空,再将其放入队列,重复上述步骤。
Java代码:
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<>();
ArrayList<TreeNode> qu= new ArrayList<>();
if(root != null){
qu.add(root);
while(qu.size() != 0){
TreeNode tmp = qu.remove(0);
res.add(tmp.val);
if(tmp.left != null)
qu.add(tmp.left);
if(tmp.right != null)
qu.add(tmp.right);
}
}
return res;
}
}
C++代码:
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> res;
deque<TreeNode*> node;
if(root != NULL)
{
node.push_back(root);
while(node.size())
{
TreeNode* tmp = node.front();
node.pop_front();
res.push_back(tmp->val);
if(tmp->left)
node.push_back(tmp->left);
if(tmp->right)
node.push_back(tmp->right);
}
}
return res;
}
};