中序遍历
递归写法
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if (root == null) return list; dfs(root, list); return list; } public void dfs(TreeNode node, List<Integer> ans) { if (node.left != null) dfs(node.left, ans); ans.add(node.val); if (node.right != null) dfs(node.right, ans); } }
非递归写法
class Solution { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<>(); if (root == null) return list; Stack<TreeNode> stack = new Stack<>(); while (!stack.isEmpty() || root != null) { while (root != null) { stack.add(root); root = root.left; } if (!stack.isEmpty()) { root = stack.pop(); list.add(root.val); root = root.right; } } return list; } }
来源:https://www.cnblogs.com/acbingo/p/9439903.html