94_二叉树的中序遍历
package 二叉树.BT; import java.util.ArrayList; import java.util.Deque; import java.util.LinkedList; import java.util.List; public class _94_二叉树的中序遍历 { 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> list = new ArrayList<>(); public List<Integer> inorderTraversal(TreeNode root) { if(root == null) return list; inorderTraversal(root.left); //拿到当前结点 list.add(root.val); inorderTraversal(root.right); return list; } // 迭代 public List<Integer> inorderTraversal2(TreeNode root) { List<Integer> list2 = new ArrayList<>(); if (root == null) return list2; Deque<TreeNode> stack = new LinkedList<>(); TreeNode node = root; while(node != null || !stack.isEmpty() ) { while(node != null) { stack.push(node); node = node.left; } node = stack.pop(); list2.add(node.val); //已经拿到当前结点了 node = node.right; } return list2; } }