366. Find Leaves of Binary Tree
MediumSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to collect nodes from a binary tree in a specific order. We need to repeatedly identify all leaf nodes, collect their values, and then remove them. This process continues until the tree becomes empty. The output should be a list of lists, where each inner list contains the values of leaves collected in one round.
Solution
Find Leaves of Binary Tree in Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findLeaves(self, root: Optional[TreeNode]) -> List[List[int]]:
result = []
def get_height(node: Optional[TreeNode]) -> int:
"""
Helper function to find the height of a node and add it to the result list.
The height of a node is its distance to the furthest leaf.
Returns the height of the current node.
"""
# Base case: a null node has a height of -1. This helps calculate leaf
# height as 0 (1 + max(-1, -1)).
if not node:
return -1
# Recursively find the height of left and right subtrees (post-order traversal).
left_height = get_height(node.left)
right_height = get_height(node.right)
# The height of the current node is 1 + max height of its children.
current_height = 1 + max(left_height, right_height)
# The height of the node determines which list it belongs to.
# If the result list is not large enough, add a new list for the current height.
if len(result) == current_height:
result.append([])
# Add the node's value to the list corresponding to its height.
result[current_height].append(node.val)
# Return the height of the current node to its parent.
return current_height
get_height(root)
return result
Find Leaves of Binary Tree in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<List<Integer>> result;
public List<List<Integer>> findLeaves(TreeNode root) {
result = new ArrayList<>();
getHeight(root);
return result;
}
// Helper function to find the height of a node and add it to the result list.
// The height of a node is its distance to the furthest leaf.
// It returns the height of the current node.
private int getHeight(TreeNode node) {
// Base case: a null node has a height of -1. This helps calculate leaf
// height as 0 (1 + max(-1, -1)).
if (node == null) {
return -1;
}
// Recursively find the height of left and right subtrees (post-order traversal).
int leftHeight = getHeight(node.left);
int rightHeight = getHeight(node.right);
// The height of the current node is 1 + max height of its children.
int currentHeight = 1 + Math.max(leftHeight, rightHeight);
// The height of the node determines which list it belongs to.
// If the result list is not large enough, add a new list for the current height.
if (result.size() == currentHeight) {
result.add(new ArrayList<>());
}
// Add the node's value to the list corresponding to its height.
result.get(currentHeight).add(node.val);
// Return the height of the current node to its parent.
return currentHeight;
}
}
Find Leaves of Binary Tree in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
vector<vector<int>> result;
// Helper function to find the height of a node and add it to the result list.
// The height of a node is its distance to the furthest leaf.
// It returns the height of the current node.
int getHeight(TreeNode* node) {
// Base case: a null node has a height of -1. This helps calculate leaf
// height as 0 (1 + max(-1, -1)).
if (!node) {
return -1;
}
// Recursively find the height of left and right subtrees (post-order traversal).
int leftHeight = getHeight(node->left);
int rightHeight = getHeight(node->right);
// The height of the current node is 1 + max height of its children.
int currentHeight = 1 + max(leftHeight, rightHeight);
// The height of the node determines which list it belongs to.
// If the result list is not large enough, add a new list for the current height.
if (currentHeight == result.size()) {
result.push_back({});
}
// Add the node's value to the list corresponding to its height.
result[currentHeight].push_back(node->val);
// Return the height of the current node to its parent.
return currentHeight;
}
public:
vector<vector<int>> findLeaves(TreeNode* root) {
getHeight(root);
return result;
}
};
Find Leaves of Binary Tree in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function findLeaves(root: TreeNode | null): number[][] {
const result: number[][] = [];
/**
* Helper function to find the height of a node and add it to the result list.
* The height of a node is its distance to the furthest leaf.
* @param node The current node.
* @returns The height of the current node.
*/
function getHeight(node: TreeNode | null): number {
// Base case: a null node has a height of -1. This helps calculate leaf
// height as 0 (1 + max(-1, -1)).
if (!node) {
return -1;
}
// Recursively find the height of left and right subtrees (post-order traversal).
const leftHeight = getHeight(node.left);
const rightHeight = getHeight(node.right);
// The height of the current node is 1 + max height of its children.
const currentHeight = 1 + Math.max(leftHeight, rightHeight);
// The height of the node determines which list it belongs to.
// If the result list is not large enough, add a new list for the current height.
if (result.length === currentHeight) {
result.push([]);
}
// Add the node's value to the list corresponding to its height.
result[currentHeight].push(node.val);
// Return the height of the current node to its parent.
return currentHeight;
}
getHeight(root);
return result;
};
More Medium LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.