DevPath

← All problems

In-Order Traversal

Easy trees · recursion

Description

Return the node values in in-order (left, node, right) for the heap-style tree.

Constraints

0 <= n <= 100000

Examples

Input: tree = [1,2,3]

Output: [2,1,3]

Hints (1)
  • Recurse left, record the node, recurse right.

Solutions

Recursive in-order. · Time O(n) · Space O(h)

func treeInorder(tree []interface{}) []int {
    out := []int{}
    var walk func(int)
    walk = func(i int) {
        if i >= len(tree) || tree[i] == nil {
            return
        }
        walk(2*i + 1)
        if n, ok := tree[i].(float64); ok {
            out = append(out, int(n))
        }
        walk(2*i + 2)
    }
    walk(0)
    return out
}

Create a free account to submit solutions, track progress and save problems.

Create account