Leetcode #145 Binary Tree postorder Traversal

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.