Niuke.com brush questions | print binary tree from top to bottom

Topic source: Niuke.com
programming connection

Topic description

Each node of the binary tree is printed from top to bottom, and the nodes of the same level are printed from left to right.

Parse:

Using a queue is actually a layer-order traversal of a binary tree, which can be achieved by using a queue, specifically BFS.

Code:

class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        queue<TreeNode*> que;
        vector<int> ret;
        if(root!=nullptr)
            que.push(root);
        while(!que.empty())
        {
            auto temp = que.front();
            que.pop();
            ret.push_back(temp->val);

            if(temp->left!=nullptr)
                que.push(temp->left);
            if(temp->right!=nullptr)
                que.push(temp->right);
        }
        return ret;
    }
};

Someone else's code:

class Solution {
public:
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        queue<TreeNode*> que;
        vector<int> ret;
        que.push(root);
        while(!que.empty())
        {
            auto temp = que.front();
            que.pop();            
            if(temp == nullptr)
                continue;
            ret.push_back(temp->val);           
            que.push(temp->left);
            que.push(temp->right);
        }
        return ret;
    }
};

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325602616&siteId=291194637