Binary Tree postorder Traversal--leetcode

Source: Internet
Author: User

Original title Link: https://oj.leetcode.com/problems/binary-tree-postorder-traversal/

Main topic: post-secondary traversal of binary tree

The way to solve the problem: the steps to traverse the binary tree: order to traverse the left subtree of the binary tree, and then traverse the right sub-tree of the binary tree, and access the root node. When a non-recursive implementation is implemented, a stack is used to simulate the traversal process. Since accessing the right subtree after the left dial hand tree has been accessed, the elements in the stack will have to move to access their right subtree, but they cannot be stacked like the first order and the middle order traversal, because the root node is last accessed. So when does the stack come out? We need a pointer to the pre to record the node of the previous visit. If the pre is the right subtree of the root node, then the right subtree of the root node is accessed, and the root node can be stacked.

Class solution{public:vector<int> Postordertraversal (TreeNode *root) {    vector<int> res;        stack<treenode*> s;        treenode* Pre=null;         while (root| |! S.empty ()) {if (root) {s.push (root); root=root->left;} else if (S.top ()->right!=pre) {root=s.top ()->right;pre=null;} Else{res.push_back (S.top ()->val);p re=s.top (); S.pop ();}}         return res;     }};

Time complexity: O (N), accessed only once per node. Space complexity: O (LgN), that is, the size of the stack tree depth.

Post-order traversal is the most difficult of the three kinds of traversal, the difference between the first sequence traversal and the middle order traversal is that a pointer is needed to help determine whether the root node can be accessed.

Binary Tree postorder Traversal--leetcode

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.