To prove safety offer- print number two fork from the top down

Title Description

Downward from the print out of each node of the binary tree, with the layer node from left to right printing.

Thinking

BFS, implemented using a queue

AC Code

#include <iostream>
#include <queue>
#include <vector>
using namespace std;

struct TreeNode
{
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL)
    {
    }
};

//先序创建
TreeNode *Create_tree()
{
    TreeNode *T;
    int val;
    cin >> val;
    if (val == 0) //叶子结点用0标记
        return NULL;
    else
    {
        T = new TreeNode(val);
        T->left = Create_tree();
        T->right = Create_tree();
    }
    return T;
}

//先序遍历
void pre_print(TreeNode *T)
{
    if (T)
    {
        cout << T->val << "  ";
        pre_print(T->left);
        pre_print(T->right);
    }
}
class Solution
{
public:
    vector<int> PrintFromTopToBottom(TreeNode *root)
    {
        queue<TreeNode *> q;
        vector<int> res;
        if (root == NULL)
            return res;
        q.push(root);
        while (!q.empty())
        {
            res.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 res;
    }
};
int main()
{
    TreeNode *root;
    root = Create_tree();
    Solution so;
    vector<int> res;
    res = so.PrintFromTopToBottom(root);
    for (vector<int>::iterator it = res.begin(); it != res.end(); it++)
    {
        cout << *it << " ";
    }
    cout << endl;

    return 0;
}
/*
测试样例:
1 2 4 0 0 5 0 0 3 6 0 0 7 0 0
1 2 3 4 5 6 7 
*/
Published 58 original articles · won praise 7 · views 2699

Guess you like

Origin blog.csdn.net/weixin_42100456/article/details/104122398