We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
C++ with iteration and an explicit stack. We (shallow) copy each node onto the stack. As we descend down the left or right of each node, we set their pointers to nullptr on the current node, so that when we return to the current node we know we've already visited them. This dovetails nicely with the leaf case, where both left and right are already null.
voidpostOrder(Node*root){if(!root)return;std::vector<Node>stack;// assuming the tree is balanced, this is enough capacity// to traverse a tree with about a million nodesconstautocap=20;stack.reserve(cap);stack.push_back(root);while(!stack.empty()){auto&top=stack.back();if(!top.left&&!top.right){std::cout<<top.data<<' ';stack.pop_back();}else{constautonext=std::exchange(top.left?:top.right,nullptr);stack.push_back(*next);}}}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Postorder Traversal
You are viewing a single comment's thread. Return to all comments →
C++ with iteration and an explicit stack. We (shallow) copy each node onto the stack. As we descend down the left or right of each node, we set their pointers to
nullptr
on the current node, so that when we return to the current node we know we've already visited them. This dovetails nicely with the leaf case, where both left and right are already null.