Binary tree level order traversal

Hello guys, I have a problem here.

Given a binary tree, return the level order traversal of its nodes' values.
For example:
Given binary tree {3,9,20,#,#,15,7},
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]

Below is my code.The result is return by function levelOrder . Where am I wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
public:
        std::vector<vector<int>> res;
        std::vector<int> temp;
            
    void addBylevel(std::queue<TreeNode*> current){
            std::queue<TreeNode*> nextLevel;
            while(!current.empty()){
            TreeNode *node=current.front();
            current.pop();
            if(node->left){
                nextLevel.push(node->left);
                temp.push_back(node->left->val);
            }
            if(node->right){
                nextLevel.push(node->right);
                temp.push_back(node->left->val);
            }
            
        }
        res.push_back(temp);
        temp.clear();
        current=nextLevel;
        addBylevel(current);
        }
        
        
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root){
            return res;
        }
        
        temp.push_back(root->val);
        res.push_back(temp);
        std::queue<TreeNode*> current;
        current.push(root);
        addBylevel(current);
        return res;
        
    }
};
Last edited on
Basically there is 3 recursive methods for traversal in a binary search tree , look for it. Each methods takes only 4 lines of codes.
Topic archived. No new replies allowed.