剑指Offer系列-面试题23:从上到下打印二叉树

来源:互联网 发布:app可视化编程软件 编辑:程序博客网 时间:2024/05/16 09:29

题目:从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。二叉树结点的定义如下:

struct TreeNode{    int val;    struct TreeNode *left;    struct TreeNode *right;};

思路:二叉树的层序遍历,用队列实现即可。

代码:

vector<int> PrintFromTopToBottom(TreeNode* root){    vector<int> result;    if(root == NULL)    {        return result;    }    queue<TreeNode*> q;    q.push(root);    TreeNode* temp;    while(!q.empty())    {        temp = q.front();        result.push_back(temp->val);        if(temp->left != NULL)        {            q.push(temp->left);        }        if(temp->right != NULL)        {            q.push(temp->right);        }        q.pop();    }    return result;}


0 0
原创粉丝点击