LeetCode 145:二叉树的后序遍历(java)
题目:
解答:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root!=null){
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
}
return list;
}
}*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
Stack<TreeNode> nodeStack=new Stack<>();
TreeNode nodeTemp=root;
TreeNode preNode=null;
while(nodeTemp!=null || !nodeStack.isEmpty()){
while(nodeTemp!=null){
nodeStack.push(nodeTemp);
nodeTemp=nodeTemp.left;
}
nodeTemp=nodeStack.peek();
if(nodeTemp.right==null || nodeTemp.right==preNode){
nodeTemp=nodeStack.pop();
list.add(nodeTemp.val);
preNode=nodeTemp;
nodeTemp=null;
}else{
nodeTemp=nodeTemp.right;
}
}
return list;
}
}