Niuke.com's sword refers to Offer - printing binary tree from top to bottom

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.

Problem solving ideas

This problem needs to be completed with the help of a queue. Every time a node is printed, if the node has child nodes, put the child nodes of the node at the end of the queue. Next, go to the head of the queue and take out the node that entered the queue earliest, and repeat the previous printing operation until all the nodes in the queue are printed out.

Take the following binary tree as an example:

1                  8
2                /  \
3               6   10
4              / \  / \
5             5  7 9  11

The steps to solve the problem are as follows:

  1. Set up a queue and add the root node to the queue. At the beginning of each loop, a node is first taken from the head of the queue, and the data value of the node is put into res (the last returned vector). At the same time, the left and right child nodes of the node are added to the queue. Corresponding to the above binary tree, the specific process is as follows:
  2. First put the root node into the queue. At the beginning of the loop, a node (ie root node 8) is taken from the head of the queue, the value of the node is put into res, and then the left and right child nodes of the node are added to the queue, namely 6 and 10;
  3. Take out node 6 from the head of the queue, put 6 into res, and add the left and right nodes (5 and 7) of node 6 to the end of the queue. At this time, the nodes in the queue are 10, 5, and 7;
  4. Take out node 10 from the head of the queue, put 10 into res, and add the left and right nodes of node 10 to the end of the queue. At this time, the queue nodes are 5, 7, 9, and 11;
  5. At this time, take out node 5 at the head of the queue, put 5 into res, and add NULL to the left and right nodes of node 5 to the end of the queue. can);
  6. Repeat the above process until all the elements in the queue are taken out, and the traversal is completed.

code

/*
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) {
        vector<int> res;
        if( root == NULL )
            return res;
        queue<TreeNode*> q;
        q.push( root );
        while( !q.empty() )
        {
            TreeNode* temp = q.front();
            q.pop();
            if( temp == NULL )
                continue;
            res.push_back(temp->val);
            q.push(temp->left);
            q.push(temp->right);
        }
        return res;
    }
};

Guess you like

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