二叉树后序遍历,分为递归方法和非递归方法:
递归:
private static List<Integer> postList = new ArrayList<>(); public static List<Integer> postorderTraversalRec(TreeNode root){ if (null == root){ return postList; } postorder(root); return postList; } private static void postorder(TreeNode root){ if (null == root){ return; } postorder(root.left); postorder(root.right); postList.add(root.val); }
非递归:
public static List<Integer> postorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if (null == root){ return list; } Stack<TreeNode> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()){ TreeNode node = stack.pop(); list.add(node.val); if (null != node.left){ stack.push(node.left); } if (null != node.right){ stack.push(node.right); } } Collections.reverse(list); return list; }