题解 | #二叉树的后序遍历#
二叉树的后序遍历
https://www.nowcoder.com/practice/1291064f4d5d4bdeaefbf0dd47d78541
import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * @param root TreeNode类 * @return int整型一维数组 */ public int[] postorderTraversal (TreeNode root) { LinkedList<TreeNode> stack = new LinkedList<>(); ArrayList<Integer> list = new ArrayList<>(); TreeNode curr = root; TreeNode pop = null; while (curr != null || !stack.isEmpty()) { if (curr != null) { stack.push(curr); curr = curr.left; } else { TreeNode peek = stack.peek(); if(peek.right == null || peek.right == pop){ pop = stack.pop(); list.add(pop.val); }else{ curr = peek.right; } } } return list.stream().mapToInt(Integer::intValue).toArray(); } }