Acwing43 not print binary tree branches from the top down

Address  https://www.acwing.com/problem/content/description/41/

Downward from the print out of each node of the binary tree, the same one node print order from left to right.

Sample

Binary input as shown [ 8 , 12 , 2 , null , null , 6 , null , 4 , null , null , null ]
     8 
   / \
   12   2 
     / 6 
   / 4 
Output: [ 8 , 12 , 2 , 6 , 4 ]
    
  

 

bfs typical example

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> res;
    queue<TreeNode* > que;
    
    void bfs()
    {
        while(!que.empty()){
            TreeNode* p = que.front();
            que.pop();
            res.push_back(p->val);
            if(p->left != NULL)
                que.push(p->left);
            if(p->right != NULL)
                que.push(p->right);
        }
    }
    
    
    vector<int> printFromTopToBottom(TreeNode* root) {
        if(root == NULL) return res;
        que.push(root);
        bfs();
        
        return res;
    }
};

 

Guess you like

Origin www.cnblogs.com/itdef/p/11331044.html