The goal is to traverse the binary tree and retrieve the maximum value from all its nodes. This can be accomplished using recursion:
Recursive Intuition: Start visiting nodes from the root. At each node, compare its value with the maximum values obtained from its left and right subtrees recursively.
Leaf Nodes: For a leaf node, its own value will be considered since there are no children.
classSolution {
// Function to find the max elementpublicintfindMax(TreeNode root) {
// Base caseif (root ==null) {
return Integer.MIN_VALUE; // If no node, return minimum integer value }
// Recursive search in left and right subtreesint leftMax = findMax(root.left);
int rightMax = findMax(root.right);
// Returning the maximum among current node, left subtree, and right subtreereturn Math.max(root.val, Math.max(leftMax, rightMax));
}
// Example usagepublicstaticvoidmain(String[] args) {
Solution sol =new Solution();
// Example tree: [10, 20, 5, 30, 35] TreeNode root =new TreeNode(10);
root.left=new TreeNode(20);
root.right=new TreeNode(5);
root.left.left=new TreeNode(30);
root.left.right=new TreeNode(35);
System.out.println("Max element is: "+ sol.findMax(root)); // Output: 35 }
}
classSolution:
# Function to find the max elementdeffindMax(self, root):
# Base caseif root isNone:
return float('-inf') # If no node, return the smallest integer value# Recursive search in left and right subtrees leftMax = self.findMax(root.left)
rightMax = self.findMax(root.right)
# Returning the maximum among current node, left subtree, and right subtreereturn max(root.val, leftMax, rightMax)
# Example usageif __name__ =="__main__":
sol = Solution()
# Example tree: [10, 20, 5, 30, 35] root = sol.TreeNode(10)
root.left = sol.TreeNode(20)
root.right = sol.TreeNode(5)
root.left.left = sol.TreeNode(30)
root.left.right = sol.TreeNode(35)
print("Max element is:", sol.findMax(root)) # Output: 35