94. 二叉树的中序遍历(迭代+递归)

120 阅读1分钟

  • 迭代法
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
       List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            list.add(root.val);
            root = root.right;
        }
        return list;
    }
}
  • 递归法
class Solution {
    private List<Integer> ans = new ArrayList<>();
    //递归遍历
    public List<Integer> inorderTraversal(TreeNode root) {
        dfs(root);
        return ans;
    }
     private void dfs(TreeNode root) {
        if (root == null) return;
        dfs(root.left);
        ans.add(root.val);
        dfs(root.right);
    }
}