Title Link: https://leetcode.com/problems/binary-tree-postorder-traversal/
(Non-recursive implementation) the sequential traversal of a binary tree.
1 classSolution2 {3 Public:4vector<int> Postordertraversal (TreeNode *root)5 {6vector<int>output;7 if(Root = =NULL)8 {9 returnoutput;Ten } One AStack<treenode*>Nodestack; -TreeNode *recentlyvisited =NULL; - the while(Root! = NULL | |!nodestack.empty ()) - { - if(Root! =NULL) - { + Nodestack.push (root); -root = root->left;//find the left-most leaf node. + } A Else //The left dial hand tree is empty. at { -root = Nodestack.top ();//rolls back a node. - if(Root->right! = NULL && root->right! = recentlyvisited)//the right subtree is not empty and has not been accessed. - { -root = root->Right ; - Nodestack.push (root); inroot = root->Left ; - } to Else //the right subtree is empty or has been visited. + { -root = Nodestack.top ();//rolls back a node. theNodestack.pop ();//Remove the node from the stack (just back off, not deleted). *Output.push_back (Root->val);//outputs the node. $recentlyvisited = root;//record the access to the right subtree (the recording process is bottom-up). Panax Notoginsengroot = NULL;//The left and right subtree output is complete, resetting the node and assigning it to the node at the top of the stack the next time it enters the loop. - } the } + } A the returnoutput; + } -};
Leetcode #145 Binary Tree postorder Traversal