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, could you do it iteratively?
每次都先push right, 然后left。 但是需要一个sentinel存每次上一次pop的node, 如果这个node是新的peek的值的子数的话,不能再push到stack,需要进入输出逻辑。 同样进入输出逻辑的还有leaf。
public IList<int> PostorderTraversal(TreeNode root) { var res = new List<int>(); var stack = new Stack<TreeNode>(); if(root == null) return res; stack.Push(root); var rightPointer = new TreeNode(-1); while(stack.Count() > 0) { if((root.right == null && root.left == null)||(root.left == rightPointer ) || (root.right == rightPointer) ) { res.Add(root.val); rightPointer = stack.Pop(); if(stack.Count()>0) root = stack.Peek(); } else { if(root.right != null) stack.Push(root.right); if(root.left != null) stack.Push(root.left); root = stack.Peek(); } } return res; }