二叉树非递归遍历
-
前序遍历
public List<Integer> preorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); Deque<TreeNode> stack = new ArrayDeque<>(); if(root == null) return res; stack.push(root); while(!stack.isEmpty()) { TreeNode curr = stack.pop(); res.add(curr.val); if(curr.right != null) stack.push(curr.right); if(curr.left != null) stack.push(curr.left); } return res; } -
中序遍历
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if(root == null) return res; Deque<TreeNode> stack = new ArrayDeque<>(); while(!stack.isEmpty() || root!=null) { while(root != null) { stack.push(root); root = root.left; } root = stack.pop(); res.add(root.val); root = root.right; } return res; } -
后序遍历
public List<Integer> postorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); if (root == null) return res; Deque<TreeNode> stack = new ArrayDeque<>(); TreeNode prev = null; while (!stack.isEmpty() || root!=null) { 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; }

浙公网安备 33010602011771号