<br />

|---|
| [![](https://www.tensorflow.org/images/GitHub-Mark-32px.png) View source on GitHub](https://github.com/keras-team/keras/tree/v3.15.1/keras/src/tree/tree_api.py#L55-L105) |

Traverses the given nested structure, applying the given function.

    tf.keras.tree.traverse(
        func, structure, top_down=True
    )

The traversal is depth-first. If `top_down` is True (default), parents
are returned before their children (giving the option to avoid traversing
into a sub-tree).

#### Examples:

    v = []
    keras.tree.traverse(v.append, [(1, 2), [3], {"a": 4}], top_down=True)
    [(1, 2), [3], {'a': 4}]
    v
    [[(1, 2), [3], {'a': 4}], (1, 2), 1, 2, [3], 3, {'a': 4}, 4]

    v = []
    keras.tree.traverse(v.append, [(1, 2), [3], {"a": 4}], top_down=False)
    [(1, 2), [3], {'a': 4}]
    v
    [1, 2, (1, 2), 3, [3], 4, {'a': 4}, [(1, 2), [3], {'a': 4}]]

<br />

<br />

<br />

| ## Args ||
|---|---|
| `func` | The function to be applied to each sub-nest of the structure. <br /> When traversing top-down: If `func(subtree) is None` the traversal continues into the sub-tree. If `func(subtree) is not None` the traversal does not continue into the sub-tree. The sub-tree will be replaced by `func(subtree)` in the returned structure (to replace the sub-tree with `None`, use the special value `MAP_TO_NONE`). When traversing bottom-up: If `func(subtree) is None` the traversed sub-tree is returned unaltered. If `func(subtree) is not None` the sub-tree will be replaced by `func(subtree)` in the returned structure (to replace the sub-tree with None, use the special value `MAP_TO_NONE`). |
| `structure` | The structure to traverse. |
| `top_down` | If True, parent structures will be visited before their children. |

<br />

<br />

<br />

<br />

| ## Returns ||
|---|---|
| The structured output from the traversal. ||

<br />

<br />

<br />

<br />

| ## Raises ||
|---|---|
| `TypeError` | If `func` is not callable. |

<br />