94. Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
二叉树的中序遍历
递归做很简单
public class BinaryTreeInorderTraversal { public List<Integer> inorderTraversal(TreeNode root) { List<Integer> res = new ArrayList<>(); dfs(root, res); return res; } public void dfs(TreeNode root, List<Integer> res) { if (root == null) { return; } dfs(root.left, res); res.add(root.val); dfs(root.right, res); } public static void main(String[] args) { TreeNode root = new TreeNode(1); root.right = new TreeNode(2); root.right.left = new TreeNode(3); BinaryTreeInorderTraversal binaryTreeInorderTraversal = new BinaryTreeInorderTraversal(); List<Integer> res = binaryTreeInorderTraversal.inorderTraversal(root); for (Integer i : res) { System.out.println(i); } } }
题目提示是否能尝试用迭代做,