题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
JAVA:
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> ans = new ArrayList<>();
ArrayList<TreeNode> queue = new ArrayList<>();
if(root==null)return ans;
queue.add(root);
while(queue.size()!=0){
TreeNode tmp = queue.remove(0);
if(tmp.left!=null)queue.add(tmp.left);
if(tmp.right!=null)queue.add(tmp.right);
ans.add(tmp.val);
}
return ans;
}
}
C++:
class Solution {
public:
vector<int> PrintFromTopToBottom(TreeNode* root) {
queue<TreeNode*>q;
q.push(root);
vector<int> ans;
if(!root)return ans;
while(!q.empty()){
ans.push_back(q.front()->val) ;
if(q.front()->left)q.push(q.front()->left);
if(q.front()->right)q.push(q.front()->right);
q.pop();
}
return ans;
}
};