代码:
package com.niuke.p6; import java.util.ArrayList; import java.util.List; import java.util.Stack; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { //二叉树的后序遍历 public ArrayList<Integer> postorderTraversal (TreeNode root) { // write code here ArrayList<Integer> list = new ArrayList<>(); if(root == null) return list; Stack<TreeNode> stack = new Stack<TreeNode>(); TreeNode pre = null; stack.push(root); while(!stack.isEmpty()) { TreeNode cur = stack.peek(); if((cur.left == null && cur.right == null)||(pre != null && (pre == cur.left || pre == cur.right))) { list.add(cur.val); stack.pop(); pre = cur; }else { if(cur.right != null) { stack.push(cur.right); } if(cur.left != null) { stack.push(cur.left); } } } return list; } }