145_二叉树的后序遍历
package 二叉树.BT; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; /** * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/submissions/ * @author Huangyujun * */ public class _145_二叉树的后序遍历 { public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode() { } TreeNode(int val) { this.val = val; } TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } } //递归 List<Integer> list1 = new ArrayList<>(); public List<Integer> postorderTraversal1(TreeNode root) { if(root == null) return list1; postorderTraversal(root.left); postorderTraversal(root.right); //拿到当前结点 list.add(root.val); return list1; } //迭代: /** 后序:【左右根】:左左左,左到不能再左了,跳出(当前结点可能是最左边的结点(是一个根(它的左是null,是它跳出的条件))),【开始找右边】: (1)没有右边/本次的右结点是上一次的结点,则本次是一个根(因为 左 右 根):添加根 prev = root; //第一次的结点,可能是下一次(根)的右结点,需要标记留个下次比较 root = null;(不加超出内存,这是why???) (2)有右边(把根push回去),从右子树开始啦:(左右根) */ List<Integer> list = new ArrayList<>(); public List<Integer> postorderTraversal(TreeNode root) { if(root == null) return list; Deque<TreeNode> stack = new LinkedList<>(); TreeNode prev = null; while(!stack.isEmpty() || root != null) { while(root != null) { stack.push(root); root = root.left; } root = stack.pop(); //右结点不存在,或者右结点是前一个遍历过的结点prev if (root.right == null || root.right == prev) { list.add(root.val); prev = root; root = null; //不加:超出内存 } else { //右结点存在 stack.push(root); root = root.right; } } return list; } }