一、Problem
給定一棵二叉樹的根 root,請你考慮它所有 從根到葉的路徑:從根到任何葉的路徑。(所謂一個葉子節點,就是一個沒有子節點的節點)
假如通過節點 node 的每種可能的 “根-葉” 路徑上值的總和全都小於給定的 limit,則該節點被稱之爲「不足節點」,需要被刪除。
請你刪除所有不足節點,並返回生成的二叉樹的根。
[1,2,-3,-5,null,4,null]
-1
提示:
給定的樹有 1 到 5000 個節點
-10^5 <= node.val <= 10^5
-10^9 <= limit <= 10^9
二、Solution
方法一:後序遍歷
思路
因爲我們要判斷以某一個結點 node 爲根的左路徑和右路徑是否滿足被刪除的要求,所以後序遍歷會是一個不錯的選擇
當遍歷到葉子結點時,如果路徑總和小於 limit 那麼該葉子結點就要被刪除,怎麼刪除呢?當然要將刪除信息傳遞給它的父親啦,所以我們的返回值選擇 bool 類型
如果某一個父親結點的左右孩子都被刪除了,證明經過父親這個結點可能的所有「根-葉」路徑的總和小於 limit,所以這個父親結點要被刪除,反之這個父節點不需要被刪除
class Solution {
boolean dfs(TreeNode root, int s, int lim) {
if (root == null)
return true;
s += root.val;
if (root.left == null && root.right == null)
return s < lim;
boolean delLeft = dfs(root.left, s, lim);
boolean delRight = dfs(root.right, s, lim);
if (delLeft) root.left = null;
if (delRight) root.right = null;
return delLeft && delRight;
}
public TreeNode sufficientSubset(TreeNode root, int limit) {
return dfs(root, 0, limit) ? null : root;
}
}
複雜度分析
- 時間複雜度:,
- 空間複雜度:,