Python - Find all the nodes at a level of a given node's level

Python - Find all the nodes at a level of a given node's level

To find all nodes at a specific level in a tree structure (assuming a binary tree for simplicity), you can perform a breadth-first search (BFS) or depth-first search (DFS) traversal while keeping track of the levels of each node. Here's how you can implement this in Python:

Example Tree Structure

Let's define a simple binary tree node class and create a sample tree for demonstration:

class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # Sample binary tree # 1 # / \ # 2 3 # / \ \ # 4 5 6 # \ # 7 root = TreeNode(1) root.left = TreeNode(2) root.right = TreeNode(3) root.left.left = TreeNode(4) root.left.right = TreeNode(5) root.right.right = TreeNode(6) root.right.right.right = TreeNode(7) 

Function to Find Nodes at a Given Level

Now, let's define a function find_nodes_at_level that uses BFS to find all nodes at a specified level in the tree:

from collections import deque def find_nodes_at_level(root, target_level): if not root: return [] queue = deque([(root, 0)]) # (node, current_level) nodes_at_level = [] while queue: node, level = queue.popleft() if level == target_level: nodes_at_level.append(node.val) elif level > target_level: break if node.left: queue.append((node.left, level + 1)) if node.right: queue.append((node.right, level + 1)) return nodes_at_level 

Usage Example

Now, let's use this function to find nodes at level 2 (for example):

level_to_find = 2 nodes_at_level = find_nodes_at_level(root, level_to_find) print(f"Nodes at level {level_to_find}: {nodes_at_level}") 

Output

For the provided sample tree, the output will be:

Nodes at level 2: [4, 5, 6] 

Explanation

  • The find_nodes_at_level function uses a BFS approach with a queue (deque from collections) to explore nodes level by level.
  • It tracks the current level of each node and collects nodes whose level matches the target_level.
  • Nodes are added to nodes_at_level list when their level matches target_level.
  • The function stops exploring deeper levels once it passes target_level, optimizing performance for large trees.

This approach efficiently finds and returns all nodes at a specified level in a binary tree using BFS traversal. Adjustments can be made for other tree structures or traversal methods as needed.

Examples

  1. Python find nodes at a specific level in a binary tree Description: Implement a function in Python to find all nodes at a specific level in a binary tree.

    class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def find_nodes_at_level(root, level): result = [] def dfs(node, current_level): if node is None: return if current_level == level: result.append(node.value) elif current_level < level: dfs(node.left, current_level + 1) dfs(node.right, current_level + 1) dfs(root, 0) return result 
  2. Python get all nodes at a specific depth in a tree Description: Write Python code to retrieve all nodes at a specific depth in a tree structure.

    class TreeNode: def __init__(self, value=0, children=None): self.value = value self.children = children or [] def find_nodes_at_depth(root, depth): result = [] def dfs(node, current_depth): if node is None: return if current_depth == depth: result.append(node.value) elif current_depth < depth: for child in node.children: dfs(child, current_depth + 1) dfs(root, 0) return result 
  3. Python find all nodes at a specific level in a graph Description: Implement a Python function to find all nodes at a specific level in an adjacency list representation of a graph.

    from collections import defaultdict, deque def find_nodes_at_level(graph, start, level): visited = set() queue = deque([(start, 0)]) result = [] while queue: node, current_level = queue.popleft() if current_level == level: result.append(node) elif current_level < level: for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append((neighbor, current_level + 1)) return result 
  4. Python BFS to find nodes at a specific level in a tree Description: Use Breadth-First Search (BFS) in Python to find all nodes at a specific level in a tree structure.

    class TreeNode: def __init__(self, value=0, children=None): self.value = value self.children = children or [] def find_nodes_at_level_bfs(root, level): queue = [(root, 0)] result = [] while queue: node, current_level = queue.pop(0) if current_level == level: result.append(node.value) elif current_level < level: for child in node.children: queue.append((child, current_level + 1)) return result 
  5. Python find all nodes at a specific depth in a binary search tree Description: Implement Python code to find all nodes at a specific depth in a binary search tree.

    class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def find_nodes_at_depth_bst(root, depth): result = [] def dfs(node, current_depth): if node is None: return if current_depth == depth: result.append(node.value) elif current_depth < depth: dfs(node.left, current_depth + 1) dfs(node.right, current_depth + 1) dfs(root, 0) return result 
  6. Python find all nodes at a specific level in a multi-way tree Description: Write Python code to find all nodes at a specific level in a multi-way tree (tree with nodes having multiple children).

    class TreeNode: def __init__(self, value=0, children=None): self.value = value self.children = children or [] def find_nodes_at_level_multiway(root, level): result = [] def dfs(node, current_level): if node is None: return if current_level == level: result.append(node.value) elif current_level < level: for child in node.children: dfs(child, current_level + 1) dfs(root, 0) return result 
  7. Python traverse tree to find nodes at a specific level Description: Traverse a tree structure in Python to find all nodes at a specific level.

    class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def find_nodes_at_level_dfs(root, level): result = [] def dfs(node, current_level): if node is None: return if current_level == level: result.append(node.value) elif current_level < level: dfs(node.left, current_level + 1) dfs(node.right, current_level + 1) dfs(root, 0) return result 
  8. Python search tree to find nodes at a specific depth Description: Perform a search in a tree structure using Python to find all nodes at a specific depth.

    class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def find_nodes_at_depth_search(root, depth): result = [] def dfs(node, current_depth): if node is None: return if current_depth == depth: result.append(node.value) elif current_depth < depth: dfs(node.left, current_depth + 1) dfs(node.right, current_depth + 1) dfs(root, 0) return result 
  9. Python find nodes at a specific level in a binary tree using DFS Description: Use Depth-First Search (DFS) in Python to find all nodes at a specific level in a binary tree.

    class TreeNode: def __init__(self, value=0, left=None, right=None): self.value = value self.left = left self.right = right def find_nodes_at_level_dfs(root, level): result = [] def dfs(node, current_level): if node is None: return if current_level == level: result.append(node.value) elif current_level < level: dfs(node.left, current_level + 1) dfs(node.right, current_level + 1) dfs(root, 0) return result 
  10. Python retrieve all nodes at a specific level in a graph using BFS Description: Implement Breadth-First Search (BFS) in Python to retrieve all nodes at a specific level in a graph.

    from collections import deque def find_nodes_at_level_graph(graph, start, level): visited = set() queue = deque([(start, 0)]) result = [] while queue: node, current_level = queue.popleft() if current_level == level: result.append(node) elif current_level < level: for neighbor in graph[node]: if neighbor not in visited: visited.add(neighbor) queue.append((neighbor, current_level + 1)) return result 

More Tags

ios-charts println drop translate3d adsi timezone-offset dst iis-7.5 displayattribute rdd

More Programming Questions

More Dog Calculators

More Statistics Calculators

More Tax and Salary Calculators

More Gardening and crops Calculators