Have written the code for level order traversal of a tree in Python. Trying to convert the same workflow to C++, but getting an error that I have mentioned at the bottom. Need some help in correcting/simplifying the code in C++. Sample i/p and o/p:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Working Python Code:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
frontier = [root]
res = [[root.val]]
while frontier:
next = []
for u in frontier:
if u.left: next.append(u.left)
if u.right: next.append(u.right)
frontier = next
res.append([node.val for node in next])
return res[:-1]
C++ code with error:
class Solution {
public:
vector<vector<int>> levelOrder(TreeNode* root) {
if(root==NULL) return {};
vector<vector<int>> res;
res.push_back({root->val});
vector<TreeNode*> frontier;
frontier.push_back(root);
while(!frontier.empty()){
vector<TreeNode*> next;
auto u = frontier.begin();
for(; u != frontier.end() ; u++){
if(u->left!=NULL) next.push_back(u->left);
if(u->right!=NULL) next.push_back(u->right);
}
frontier = next;
vector<int> temp;
while(!next.empty()){
temp.push_back(next.back()->val);
next.pop_back();
}
res.push_back(temp);
}
return res;
}
};
Error: Char 23: error: request for member 'left' in '* u.__gnu_cxx::__normal_iterator<TreeNode**, std::vector<TreeNode*> >::operator->()', which is of pointer type 'TreeNode*' (maybe you meant to use '->' ?)