742 Closest Leaf in a Binary Tree
1. Question
Given a binary tree where every node has a unique value, and a target keyk, find the value of the nearest leaf node to targetkin the tree.
Here,nearest to a leaf means the least number of edges travelled on the binary tree to reach any leaf of the tree. Also, a node is called aleafif it has no children.
In the following examples, the input tree is represented in flattened form row by row. The actualroottree given will be a TreeNode object.
Example 1:
Input: root = [1, 3, 2], k = 1
Diagram of binary tree:
1
/ \
3 2
Output: 2 (or 3)
Explanation: Either 2 or 3 is the nearest leaf node to the target of 1.Example 2:
Example 3:
Note:
rootrepresents a binary tree with at least1node and at most1000nodes.Every node has a unique
node.valin range[1, 1000].There exists some node in the given binary tree for which
node.val == k.
2. Implementation
(1) DFS + BFS
思路: 1. DFS to construct graph
BFS to find the closet leaf node
3. Time & Space Complexity
DFS + BFS : 时间复杂度O(n), 空间复杂度O(n)
Last updated
Was this helpful?