Algo-Sim › Binary Trees & BST

Inorder Traversal (Recursive)

Easy · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Recursive depth-first traversal that outputs each node between the left and right subtrees.

Problem

Given the root of a binary tree, return its values in inorder: the left subtree, then the node, then the right subtree. This version recurses.

Constraints

Edge cases to test

Follow-up questions

Can you do it in O(1) extra space?
Morris traversal threads each inorder predecessor’s right pointer back to its successor, then removes the thread: O(n) time, O(1) space.
How do you check a BST with it?
Inorder must be strictly increasing, so compare each value with the previous one: O(n), O(h).

Solution

Java

public List<Integer> inorderTraversal(TreeNode root) {
    List<Integer> out = new ArrayList<>();
    visit(root, out);
    return out;
}

private void visit(TreeNode node, List<Integer> out) {
    if (node == null) return;
    visit(node.left, out);
    out.add(node.val);
    visit(node.right, out);
}

Python

def inorder_traversal(root):
    out = []

    def visit(node):
        if not node:
            return
        visit(node.left)
        out.append(node.val)
        visit(node.right)

    visit(root)
    return out

C++

#include <bits/stdc++.h>
using namespace std;
class Solution {
  public:
    vector<int> inorderTraversal(TreeNode *root) {
        vector<int> out;
        visit(root, out);
        return out;
    }
    void visit(TreeNode *node, vector<int> &out) {
        if (!node)
            return;
        visit(node->left, out);
        out.push_back(node->val);
        visit(node->right, out);
    }
};

More Binary Trees & BST problems