剑指offer 从上往下打印二叉树

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。
思路:层次遍历,使用queue,压入根节点,然后看左右子树,只要不为空就继续压进去。
/*
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) {
        queue<TreeNode*> q;
        vector<int> result;      
         if(root == nullptr){
             return result;
         }  
        q.push(root);
        while(!q.empty()){
            TreeNode* tmp = q.front();
            q.pop();
            result.push_back(tmp -> val);
            if(tmp -> left != nullptr){
                q.push(tmp -> left);
            }
            if(tmp -> right != nullptr){
                q.push(tmp -> right);
            }
        }
        return result;
    }
};
原文地址:https://www.cnblogs.com/dingxiaoqiang/p/7469600.html