The problem is to find all the full nodes in a binary tree. A full node in a binary tree is defined as a node that has both left and right children present. We need to return or print all such nodes.
Input:
Binary Tree:
1/ \
23/ \
45 Output: [1, 2]
Explanation: Node 1 has both children (2and3), and Node 2 has both children (4and5). Hence, they are full nodes
Input:
Binary Tree:
10/ \
2030/ \
4050Output: [10, 30]
Explanation: Node 10 has both children (20and30), and Node 30 has both children (40and50). Hence, they are full nodes.
The intuition behind the problem lies in understanding what constitutes a “full node.” To determine whether a node is a full node:
Check if the left child is present.
Check if the right child is present.
This can be achieved using traversal techniques such as pre-order, in-order, or post-order. During the traversal, we check the condition for each node and add it to the result if it qualifies as a full node.
classSolution:
deffindFullNodes(self, root):
full_nodes = []
self._find_full_nodes_helper(root, full_nodes)
return full_nodes
def_find_full_nodes_helper(self, node, full_nodes):
ifnot node:
return# Check if it is a full nodeif node.left and node.right:
full_nodes.append(node.val)
# Recursive calls for left and right children self._find_full_nodes_helper(node.left, full_nodes)
self._find_full_nodes_helper(node.right, full_nodes)
# Main function to test the codeif __name__ =="__main__":
# Example Tree: 1 -> [2, 3] -> [4, 5] root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
solution = Solution()
print(solution.findFullNodes(root)) # Output: [1, 2]
Objective: Given a binary tree, print all nodes will are full nodes.
Full Nodes: Nodes Which has both the children, left and right are called Full Nodes
Approach:
quite simple Solution.
Do the any of the traversal (inorder, preorder, postorder etc).
During traversal, check the node if it has left child and right child, If yes then print it
Complete Code:
1
2
3
4
5
6
7
8
9
10
11
12
publicvoidFindFullNodes(Node root) {
// do the traversal and print all the nodes which has left and right// childif (root !=null) {
FindFullNodes(root.left);
if (root.left!=null&& root.right!=null) {
System.out.print(root.data+" ");
}
FindFullNodes(root.right);
}
}