Leetcode: Binary Tree postorder traversal [145]

Source: Internet
Author: User
[Question]

Given a binary tree, return the postorder traversal of its nodes 'values.

For example:
Given Binary Tree{1,#,2,3},

   1         2    /   3

Return[3,2,1].

Note: recursive solution is trivial, cocould You Do It iteratively?


Question]

Non-recursive Traversal


[Idea]

Maintain two stacks. One stack is used to store tags, and the right subtree of the corresponding node is traversed. The other stack is used to simulate post-sequential traversal.


[Code]
/*** Definition for binary tree * struct treenode {* int val; * treenode * left; * treenode * right; * treenode (int x): Val (x ), left (null), right (null) {}*}; */class solution {public: vector <int> postordertraversal (treenode * root) {vector <int> result; treenode * node = root; stack <treenode *> st; stack <bool> st_flag; while (node) {St. push (node); st_flag.push (false); node = node-> left;} while (! St. Empty () {bool status = st_flag.top (); If (! Status) {// access the right subtree st_flag.pop (); st_flag.push (true); node = ST. top (); node = node-> right; while (node) {St. push (node); st_flag.push (false); node = node-> left ;}} else {// access the current node st_flag.pop (); node = ST. top (); ST. pop (); result. push_back (node-> Val) ;}} return result ;}};


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.