Given the root of a binary tree, write a function to return or print all the leaf nodes of the tree. A leaf node is a node that does not have any children (both left and right are null).
Input:
Binary Tree:
1/ \
23/ \
45Output:
Leaf Nodes: [2, 4, 5]
Explanation:
The leaf nodes in the binary tree are the nodes without children. Here, nodes with values `2`, `4`, and`5` are leaf nodes.
Input:
Binary Tree:
10/20/ \
3040Output:
Leaf Nodes: [30, 40]
Explanation:
The leaf nodes in the binary tree are nodes with values `30`and`40`, since these nodes have no children.
classSolution:
defgetLeafNodes(self, root):
# Helper function to collect leaf nodesdefdfs(node, leaf_nodes):
if node isNone:
return# Check if the current node is a leafif node.left isNoneand node.right isNone:
leaf_nodes.append(node.val)
# Recursively traverse left and right children dfs(node.left, leaf_nodes)
dfs(node.right, leaf_nodes)
# List to store the leaf nodes leaf_nodes = []
dfs(root, leaf_nodes)
return leaf_nodes
# Examplesroot = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.right.left = TreeNode(4)
root.right.right = TreeNode(5)
solution = Solution()
print(solution.getLeafNodes(root)) # Output: [2, 4, 5]