while cond1
...
if cond2
...
else
...
break
The while
loop above has two termination conditions,
cond2
and!cond1
!cond2
When the commands that are represented by ...
are long,
I feel the code is not easy to understand.
The two termination conditions for the same while-loop are far apart.
See when using break is bad.
Is there a better way to write such code for easier to be understood? For example, can we avoid writing the two termination conditions in two separate places?
My question comes from reading a C++ program, but is actually not specific to programming languages. Just assume usual control constructs available in programming languages.
A non-recursive implementation of postorder traversal of a binary tree, using stack
vector<int> postorderTraversal(TreeNode *root) {
vector<int> result;
stack<const TreeNode *> s;
const TreeNode *p = root, *q = nullptr;
do {
while (p != nullptr) {
s.push(p);
p = p->left;
}
q = nullptr;
// start of the example
while (!s.empty()) {
p = s.top();
s.pop();
if (p->right == q) {
result.push_back(p->val);
q = p;
} else {
s.push(p);
p = p->right;
break; //<=== exit inner loop
}
}
// end of example
} while (!s.empty()); //end do..while
return result;
}