94_二叉树的中序遍历
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; } }
本文来自博客园,作者:一乐乐,转载请注明原文链接:https://www.cnblogs.com/shan333/p/15709266.html