[抄題]:node
We are given a binary tree (with root node root
), a target
node, and an integer value K
.算法
Return a list of the values of all nodes that have a distance K
from the target
node. The answer can be returned in any order.數據結構
Example 1:ide
Input: root = [3,5,1,6,2,0,8,null,null,7,4], target = 5, K = 2 Output: [7,4,1] Explanation: The nodes that are a distance 2 from the target node (with value 5) have values 7, 4, and 1.
Note that the inputs "root" and "target" are actually TreeNodes. The descriptions of the inputs above are just serializations of these objects.
Note:優化
0 <= node.val <= 500
.target
node is a node in the tree.0 <= K <= 1000
.[暴力解法]:spa
時間分析:debug
空間分析:code
[優化後]:blog
時間分析:遞歸
空間分析:
[奇葩輸出條件]:
[奇葩corner case]:
[思惟問題]:
沒啥思路,覺得是dfs就能夠了。可是其實分爲兩步:
存儲:把root,左右長度存在map中
取出來:length每次加一,遞增爲k
[英文數據結構或算法,爲何不用別的數據結構或算法]:
[一句話思路]:
[輸入量]:空: 正常狀況:特大:特小:程序裏處理到的特殊狀況:異常狀況(不合法不合理的輸入):
[畫圖]:
[一刷]:
[二刷]:
[三刷]:
[四刷]:
[五刷]:
[五分鐘肉眼debug的結果]:
[總結]:
先在左邊右邊用dfs生成長度,存map。再用dfs的length+1找出全部節點
[複雜度]:Time complexity: O(n) Space complexity: O(n)
[算法思想:迭代/遞歸/分治/貪心]:
[關鍵模板化代碼]:
int left = find(root.left, target, K); if (left >= 0) { map.put(root, left + 1); return left + 1; }
[其餘解法]:
[Follow Up]:
[LC給出的題目變變變]:
[代碼風格] :
[是否頭一次寫此類driver funcion的代碼] :
[潛臺詞] :
class Solution { //initialization: hashmap HashMap<TreeNode, Integer> map = new HashMap<TreeNode, Integer>(); public List<Integer> distanceK(TreeNode root, TreeNode target, int K) { List<Integer> result = new ArrayList<Integer>(); find(root, target, K); dfs(root, 0, target, K, result); return result; } //find and store length public int find(TreeNode root, TreeNode target, int K) { //corner case: root == null if (root == null) return -1; //root.val == target if (target == root) { map.put(root, 0); return 0; } //define left, right and add int left = find(root.left, target, K); if (left >= 0) { map.put(root, left + 1); return left + 1; } int right = find(root.right, target, K); if (right >= 0) { map.put(root, right + 1); return right + 1; } return -1; } //add the points to res public void dfs(TreeNode root, int length, TreeNode target, int K, List<Integer> res) { //corner case if (root == null) return ; //get length if there is key if (map.containsKey(root)) { length = map.get(root); } //add to res if (length == K) res.add(root.val); //dfs in left and right dfs(root.left, length + 1, target, K, res); dfs(root.right, length + 1, target, K, res); } }