题目:牛客网
解题思路:
链接:https://www.nowcoder.com/questionTerminal/32af374b322342b68460e6fd2641dd1b?f=discussion
来源:牛客网
要保证根结点在左孩子和右孩子访问之后才能访问,因此对于任一结点P,先将其入栈。
如果P不存在左孩子和右孩子,则可以直接访问它;
或者P存在孩子,但是其孩子都已被访问过了,则同样可以直接访问该结点
若非上述两种情况,则将P的右孩子和左孩子依次入栈,这样就保证了
每次取栈顶元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子都在根结点前面被访问。
import java.util.ArrayList;
import java.util.Stack;
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
if(null == root){
return res;
}
TreeNode pre = null;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.add(root);
while(!stack.isEmpty()){
TreeNode current = stack.peek();
if((current.left == null && current.right == null)||(pre!=null &&(pre==current.left || pre == current.right))){
res.add(current.val);
stack.pop();
pre = current;
}
else{
if(current.right != null){
stack.add(current.right);
}
if(current.left != null){
stack.add(current.left);
}
}
}
return res;
}
}