Problem:
Given a binary tree where every node has a unique value, and a target key k
, find the value of the closest leaf node to target k
in the tree.
Here, closest 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 a leaf if it has no children.
In the following examples, the input tree is represented in flattened form row by row. The actual root
tree given will be a TreeNode object.
Example 1:
1 2 3 4 5 6 7 8 9 10 |
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 closest leaf node to the target of 1. |
Example 2:
1 2 3 4 5 |
Input: root = [1], k = 1 Output: 1 Explanation: The closest leaf node is the root node itself. |
Example 3:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Input: root = [1,2,3,4,null,null,null,5,null,6], k = 2 Diagram of binary tree: 1 / \ 2 3 / 4 / 5 / 6 Output: 3 Explanation: The leaf node with value 3 (and not the leaf node with value 6) is closest to the node with value 2. |
Note:
root
represents a binary tree with at least1
node and at most1000
nodes.- Every node has a unique
node.val
in range[1, 1000]
. - There exists some node in the given binary tree for which
node.val == k
.
题目大意:
给你一棵树,每个节点的值都不相同。
给定一个节点值,让你找到离这个节点距离最近的叶子节点的值。
Idea:
Shortest path from source to any leaf nodes in a undirected unweighted graph.
问题转换为在无向/等权重的图中找一条从起始节点到任意叶子节点最短路径。
Solution:
C++ / DFS + BFS
Time complexity: O(n)
Space complexity: O(n)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
// Author: Huahua // Runtime: 16 ms class Solution { public: int findClosestLeaf(TreeNode* root, int k) { graph_.clear(); start_ = nullptr; buildGraph(root, nullptr, k); queue<TreeNode*> q; q.push(start_); unordered_set<TreeNode*> seen; while (!q.empty()) { int size = q.size(); while (size-->0) { TreeNode* curr = q.front(); q.pop(); seen.insert(curr); if (!curr->left && !curr->right) return curr->val; for (TreeNode* node : graph_[curr]) if (!seen.count(node)) q.push(node); } } return 0; } private: void buildGraph(TreeNode* node, TreeNode* parent, int k) { if (!node) return; if (node->val == k) start_ = node; if (parent) { graph_[node].push_back(parent); graph_[parent].push_back(node); } buildGraph(node->left, node, k); buildGraph(node->right, node, k); } unordered_map<TreeNode*, vector<TreeNode*>> graph_; TreeNode* start_; }; |
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment