class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
class LinkedListNode {
int val;
LinkedListNode next;
LinkedListNode(int val) { this.val = val; }
}
public class HierarchyDemo {
public static void main(String[] args) {
// Build tree
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
// Build array
int[] arr = {1, 2, 3, 4, 5};
// Build linked list
LinkedListNode head = new LinkedListNode(1);
head.next = new LinkedListNode(2);
head.next.next = new LinkedListNode(3);
head.next.next.next = new LinkedListNode(4);
head.next.next.next.next = new LinkedListNode(5);
// Find children of node 2 in tree
System.out.print("Tree children of 2: ");
printTreeChildren(root, 2);
// Find children of node 2 in array
System.out.print("Array children of 2: ");
printArrayChildren(arr, 2);
// Find children of node 2 in linked list
System.out.print("Linked List children of 2: ");
printLinkedListChildren(head, 2);
}
static void printTreeChildren(TreeNode node, int target) {
if (node == null) return;
if (node.val == target) {
if (node.left != null) System.out.print(node.left.val + " ");
if (node.right != null) System.out.print(node.right.val + " ");
System.out.println();
return;
}
printTreeChildren(node.left, target);
printTreeChildren(node.right, target);
}
static void printArrayChildren(int[] arr, int target) {
// No hierarchy, so no children
System.out.println("None");
}
static void printLinkedListChildren(LinkedListNode head, int target) {
// No hierarchy, so no children
System.out.println("None");
}
}if (node.val == target) {
Check if current node is the target to find children
if (node.left != null) System.out.print(node.left.val + " ");
Print left child if exists
if (node.right != null) System.out.print(node.right.val + " ");
Print right child if exists
System.out.println("None");
Print None for no children in array or linked list
Tree children of 2: 4 5
Array children of 2: None
Linked List children of 2: None