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