Tree Traversal
Tree Traversal
Idea behind using a stack
std::vector<TreeNode*> goldenTraversal(TreeNode* root) {
// key: keep diving to the left
std::vector<TreeNode*> res;
std::stack<TreeNode*> stack; // stores the node that hasn't traced the right branch
TreeNode* curNode = root;
while(!stack.empty() || curNode) {
while (curNode) {
stack.push(curNode);
//res.push_back(curNode); // preorder use this one
curNode = curNode->left;
}
curNode = stack.top();
stack.pop();
//res.push_back(curNode); // inorder use this one
curNode = curNode->right;
}
return res;
}For postorder, key point is to pop the node only when right child has been traversed.
Last updated