# TreePosition TreePosition[tree,pattern]

gives a list of the positions of subtrees of tree whose data matches pattern.

TreePosition[tree,pattern,levelspec]

finds only matches that appear on levels of tree specified by levelspec.

TreePosition[tree,pattern,levelspec,n]

gives the positions of the first n matches found.

TreePosition[pattern]

represents an operator form of TreePosition that can be applied to a tree.

# Details • In TreePosition[tree,pattern], tree must be a valid Tree object.
• TreePosition[tree,pattern] tests all the subtrees of tree in turn to try to find ones with data that match pattern.
• TreePosition returns a list of positions in a form suitable for use in TreeExtract.
• The default level specification for TreePosition is {0,Infinity}.
• A part specification {} returned by TreePosition represents the whole of tree.
• TreePosition uses standard level specifications:
•  n levels 1 through n Infinity levels 1 through Infinity {n} level n only {n1,n2} levels n1 through n2
• A positive level n+1 consists of all subtrees of tree that are children of subtrees on level n.
• Level 0 corresponds to the root of the tree.
• Level -1 corresponds to the leaves.
• A negative level -(n+1) consists of all subtrees whose children are on levels -1, -2, , -n, with highest level -n.
• TreePosition traverses subtrees in a left-to-right, depth-first order, yielding lists of indices in lexicographic order.
• TreePosition[pattern][tree] is equivalent to TreePosition[tree,pattern].

# Examples

open allclose all

## Basic Examples(3)

Find the positions of the subtrees whose data is an even number:

Find the positions of the subtrees in the first level whose data is an even number:

Find the positions of the leaves whose data is an even number:

## Scope(5)

Find the positions of the subtrees whose data is an odd integer:

Find the positions of the subtrees at levels 0, 1 and 2 whose data is an odd integer:

Find the positions of the leaf subtrees whose data is an odd integer:

Find the positions of the inner subtrees whose data is an odd integer:

Find the first four positions of the subtrees whose data is an odd integer:

## Applications(1)

Compute the level with the most nodes:

## Properties & Relations(2)

Position[expr,pattern,levelspec] is equivalent to TreePosition[ExpressionTree[expr,"Arguments"],pattern,levelspec]:

Position[expr,pattern,levelspec,HeadsTrue] is equivalent to TreePosition[ExpressionTree[expr,"Subexpressions"],pattern,levelspec]-1 for positive levels