Grokking Graph Algorithms for Coding Interviews
Ask Author
Back to course home

0% completed

Vote For New Content
All Nodes Distance K in Binary Tree (medium)
Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Problem Statement

Given the root of a binary tree, a target node, and a distance k, find all the nodes in the tree that are exactly k edges away from the target node. You may return these nodes' values in any order.

Examples

Example 1

  • Input: root = [1, 2, 3, 4, 5, null, 6, 7, 8], target = 3, k = 1
Image
  • Expected Output: [6, 1]
  • Justification: Nodes 1 and 6 are one edge away from node 3.

Example 2

  • Input: root = [1, 2, 3, null, 4, 5, 6], tarrget = 2, k = 2
Image
  • Expected Output: [3]
  • Justification: Node 3 is two edges away from node 2.

Example 3

  • Input: root = [1, 2, 3, 4, 5, null, null, null, null, 6, 7], target = 4, k = 3
Image
  • Expected Output: [6, 7, 3]
  • Justification: Nodes 6, 7 and 3 are three edges away from node 4.

Constraints:

  • The number of nodes in the tree is in the range [1, 500].
  • 0 <= Node.val <= 500
  • All the values Node.val are unique.
  • target is the value of one of the nodes in the tree.
  • 0 <= k <= 1000

Try it yourself

Try solving this question here:

Python3
Python3

. . . .

.....

.....

.....

Like the course? Get enrolled and start learning!

Table of Contents

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible

Contents are not accessible