题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
解题思路
bfs
Code
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
vector<int> res;
if(root == nullptr) {
return res;
}
queue<TreeNode *> q;
q.push(root);
while(!q.empty()) {
TreeNode *curr = q.front();
q.pop();
res.push_back(curr->val);
if(curr->left) {
q.push(curr->left);
}
if(curr->right) {
q.push(curr->right);
}
}
return res;
}
};
- java
import java.util.ArrayList;
import java.util.LinkedList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
if(root != null) {
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode cur = queue.peek();
queue.pop();
result.add(cur.val);
if(cur.left != null) {
queue.add(cur.left);
}
if(cur.right != null) {
queue.add(cur.right);
}
}
}
return result;
}
}