Topic:
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] .
Solving:
Recursion is the same as the previous sequence and the first order, just exchange the order
public static list<integer> result=new arraylist<integer> (); public static list<integer> postordertraversal (TreeNode root) { if (root!=null) {postordertraversal ( Root.right); Postordertraversal (Root.left); Result.add (Root.val); } return result;
The iterations are slightly more complex and the solution is the same as the previous one, but this is the first to access the left and right nodes, the same as the main line, but to add a stack here to record whether each node has been access to the nodes, only if the left and the same access to the node can access the root node
public static list<integer> PostorderTraversal2 (TreeNode root) { list<integer> res=new arraylist< > (); Stack<treenode> nodestack=new stack<> (); Stack<integer> nodestate=new stack<> ();//record whether the right node has been accessed, 1 indicates that it has been accessed, and 0 indicates that the if (root==null) return res is not accessed; else {nodestack.push (root); Nodestate.push (0); root=root.left;} while (!nodestack.isempty ()) {while (root!=null) {nodestack.push (root); Nodestate.push (0); root=root.left;} When this loop jumps out, it shows that the node at the top of the Nodestak stack has no left node if (Nodestate.peek () ==1)//If the right node has been accessed at this time, then the root node {res.add can be accessed. Nodestack.pop (). val); Nodestate.pop ();//Remove the state value corresponding to the root node } else {//Access Right node Root=nodestack.peek (). Right;nodestate.pop ();//change state value from 0 to 1 Nodestate.push (1);} } return res;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
LeetCode145 Binary Tree postorder traversal java (recursive iteration)