Leetcode 1080. Insufficient nodes on the root to leaf path
topic
给定一棵二叉树的根 root,请你考虑它所有 从根到叶的路径:从根到任何叶的路径。(所谓一个叶子节点,就是一个没有子节点的节点)
假如通过节点 node 的每种可能的 “根-叶” 路径上值的总和全都小于给定的 limit,则该节点被称之为「不足节点」,需要被删除。
请你删除所有不足节点,并返回生成的二叉树的根。
Example 1:
输入:root = [1,2,3,4,-99,-99,7,8,9,-99,-99,12,13,-99,14], limit = 1
输出:[1,2,3,4,null,null,7,8,9,null,14]
Example 2:
输入:root = [5,4,8,11,null,17,4,7,1,null,null,5,3], limit = 22
输出:[5,4,8,11,null,17,4,7,null,null,null,5]
Example 3:
输入:root = [5,-6,-6], limit = 0
输出:[]
Ideas
- Recursion is preferred for tree problems
- dfs uses post-order traversal, there are 2 reasons
- Need to record the sum of the previous nodes, if you use the preorder, you have to traverse again
- Post-order can prevent broken link
- When the left and right are insufficient nodes, the root must be the insufficient node
- The left is an insufficient node, the right does not exist, and the root is also an insufficient node
- The left does not exist, the right is an insufficient node, and the root is also an insufficient node
- Note that when root is empty, sum <limit is used to judge, and you will know the specific reason by drawing a picture.
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool dfs(TreeNode*& root, int sum, int limit) {
if (!root) return sum < limit;
bool left = dfs(root->left, sum + root->val, limit);
bool right = dfs(root->right, sum + root->val, limit);
if (left && right) {
root = NULL;
return true;
}
if (left && !root->right) {
root = NULL;
return true;
}
if (!root->left && right) {
root = NULL;
return true;
}
return false;
}
TreeNode* sufficientSubset(TreeNode* root, int limit) {
dfs(root, 0, limit);
return root;
}
};