[抄題]:node
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.ide
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:spa
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.
[暴力解法]:debug
時間分析:rest
空間分析:code
[優化後]:
時間分析:
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思惟問題]:
不知道還要找點,把路徑存在hashmap中
[英文數據結構或算法,爲何不用別的數據結構或算法]:
[一句話思路]:
bfs的過程當中,cur節點的左、右、map中存儲的路徑都要放進q
[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):
[畫圖]:
[一刷]:
- dfs函數的做用是返回有效的 值爲k的節點,因此結果是左右節點的時候也須要返回
- 左右節點均爲空的時候,再返回root.val的數值
[二刷]:
- dfs函數中,先把左節點放進去,再返回整個的left
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
用map存路徑map.put(root.left, root);,而後用dfs找到k
[複雜度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
[其餘解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
[是否頭一次寫此類driver funcion的代碼] :
[潛臺詞] :


/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public int findClosestLeaf(TreeNode root, int k) { //corner case if (root == null) return -1; //initialiazation: map, q //put first node into q, add left, right, route HashMap<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>(); PriorityQueue<TreeNode> q = new PriorityQueue<TreeNode>(); TreeNode match = dfsTree(k, root, map); q.add(match); while (!q.isEmpty()) { TreeNode cur = q.poll(); if (cur.left == null && cur.right == null) return cur.val; if (cur.left != null) q.add(cur.left); if (cur.right != null) q.add(cur.right); if (map.containsKey(cur)) { q.add(map.get(cur)); map.remove(cur); } } return -1; } public TreeNode dfsTree(int k, TreeNode root, Map<TreeNode, TreeNode> map) { //corner case : null if (root == null) return null; //return if left & right is null if (root.val == k) return root; //put left into map and return left if (root.left != null) { map.put(root.left, root); TreeNode left = dfsTree(k, root.left, map); if (left != null) return left; } //put left into map and return left if (root.right != null) { map.put(root.right, root); TreeNode right = dfsTree(k, root.right, map); if (right != null) return right; } //return null return null; } }