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]
.
/*** Definition for a binary tree node. * public class TreeNode {* int val; * TreeNode left; * TreeNode rig Ht * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicList<integer>postordertraversal (TreeNode root) {//The post-order traversal and the middle sequence traversal are different because the root node needs to be accessed after the left and right nodes, so when you save the record, you need to determine whether a node is a leaf node, and//if his child has traversed, use Mark to mark it, indicating that the child has traversed. Note the order in which the child nodes are added to the stack, push the right node first, and then push the child nodelist<integer>res=NewArraylist<integer>(); if(root==NULL)returnRes; Stack<TreeNode> stack=NewStack<treenode>(); Stack.push (root); TreeNode Mark=root;//represents a node that has already been visited while(!Stack.isempty ()) {TreeNode node=Stack.peek (); if(node.left==NULL&&node.right==NULL|| node.left==mark| | node.right==Mark) {Res.add (node.val); Mark=node; Stack.pop (); }Else{ if(node.right!=NULL){//////OrderStack.push (node.right); } if(node.left!=NULL) {Stack.push (node.left); } } } returnRes; } /*list<integer> Res; Public list<integer> postordertraversal (TreeNode root) {res=new arraylist<integer> (); if (root==null) return res; Getres (root); return res; public void Getres (TreeNode root) {if (root==null) return; Getres (Root.left); Getres (Root.right); Res.add (Root.val); }*/}
[Leedcode 145] Binary Tree postorder Traversal