I've been repeating a chunk of similar code for several times. This how it's like in pseudo code:
stack.push(root)
while stack size > 0
node = stack.pop()
if condition_1
if node is leaf
if condition_2
// do something,
// for example, push node into a vector and return the vector
else
stack.push(children of node)
or like this:
stack.push(root)
while stack size > 0
node = stack.pop()
if condition_1
if node is leaf
if condition_2 // or no condition_2 and return true directly
return true
else
stack.push(children of node)
return false
The difference between this two snippets is that the first one iterates all leaf nodes, while the second one has a break logic. And usually the main work I do is condition_2
and what's in its scope. Other lines are just repeating themselves.
So is there a way to extract this kind of tree iterating loop, in C++ or any other language?