树的遍历——迭代

ztzzh-1 / 2023-09-05 / 原文

/*中序遍历*/

class
Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); Deque<TreeNode> stack=new LinkedList<>(); while(root!=null || !stack.isEmpty()){ while(root!=null){ stack.push(root); root=root.left; } root=stack.pop(); list.add(root.val); root=root.right; } return list; } }
/*前序遍历*/

class
Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> list=new ArrayList<>(); Deque<TreeNode> stack=new LinkedList<>(); while(!stack.isEmpty() || root!=null){ while(root!=null){ list.add(root.val); stack.push(root); root=root.left; } root=stack.pop(); root=root.right; } return list; } }
/*后序遍历*/

class
Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<Integer>(); if (root == null) { return res; } Deque<TreeNode> stack = new LinkedList<TreeNode>(); TreeNode prev = null; while (root != null || !stack.isEmpty()) { while (root != null) { stack.push(root); root = root.left; } root = stack.pop(); if (root.right == null || root.right == prev) { res.add(root.val); prev = root; root = null; } else { stack.push(root); root = root.right; } } return res; } }