742. Closest Leaf in a Binary Tree查找最近的葉子節點
[抄題]:
Given a binary tree where every node has a unique value, and a target key k
, find the value of the nearest leaf node to target k
in 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 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:
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:
Input:
root = [1], k = 1
Output: 1
Explanation: The nearest leaf node is the root node itself.
Example 3:
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 nearest to the node with value 2.
[暴力解法]:
時間分析:
空間分析:
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思維問題]:
不知道還要找點,把路徑存在hashmap中
[英文數據結構或算法,為什麽不用別的數據結構或算法]:
[一句話思路]:
[輸入量]:空: 正常情況:特大:特小:程序裏處理到的特殊情況:異常情況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
[復雜度]:Time complexity: O() Space complexity: O()
[算法思想:叠代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
[其他解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
[是否頭一次寫此類driver funcion的代碼] :
[潛臺詞] :
742. Closest Leaf in a Binary Tree查找最近的葉子節點