In a tree data structure, a leaf node (also called a terminal node) is a node that does not have any children. In other words, a leaf node is a node that is at the end of a branch and has no further sub-nodes. A leaf node is also commonly referred to as a “terminal” node because it is the last node in a path through the tree. Leaf nodes are important in many tree-based algorithms, as they often represent the end points of a traversal or search operation. In a binary tree, every node can have at most two children, and so the leaf nodes are the nodes that have no children at all.
data class TreeNode(val value: Int, val left: TreeNode? = null, val right: TreeNode? = null)
fun findLeaves(root: TreeNode?) {
if (root == null) {
return
}
if (root.left == null && root.right == null) {
println(root.value)
return
}
findLeaves(root.left)
findLeaves(root.right)
}
fun main() {
val tree = TreeNode(
1,
TreeNode(2, TreeNode(4), TreeNode(5)),
TreeNode(3, TreeNode(6), TreeNode(7))
)
println("Leaf nodes of the binary tree are:")
findLeaves(tree)
}
This code defines a simple binary tree using a TreeNode
data class. Each node in the tree contains an integer value and references to its left and right child nodes.
The findLeaves()
function takes a TreeNode
as its argument and recursively finds all the leaf nodes in the tree. If the current node is a leaf node (i.e., it has no left or right children), the function prints its value. If the current node is not a leaf node, the function recursively calls itself on the left and right child nodes of the current node.
In the main()
function, we define a binary tree and call the findLeaves()
function with the root node of the tree. The function prints all the leaf nodes in the tree.
Note that this implementation assumes a binary tree, which means that each node can have at most two children. If you have a tree with more than two children per node, you’ll need to modify the implementation to handle that case.