-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsufficient_node_in_binary_tree.cpp
More file actions
51 lines (47 loc) · 1.29 KB
/
Insufficient_node_in_binary_tree.cpp
File metadata and controls
51 lines (47 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
TreeNode* check_tree(TreeNode* root, int limit){
if(root->left == NULL && root->right == NULL){
if(root->val < limit){
return NULL;
}
return root;
}
if(root->left != NULL){
root->left = check_tree(root->left, limit - root->val);
}
if(root->right != NULL){
root->right = check_tree(root->right, limit - root->val);
}
if(root->left == root->right){
root = NULL;
}
return root;
}
class Solution {
public:
TreeNode* sufficientSubset(TreeNode* root, int limit) {
return check_tree(root, limit);
}
};
//////////////////////////////////////////////////////////
// simple approach
class Solution {
public:
TreeNode* sufficientSubset(TreeNode* root, int limit) {
if (root->left == root->right)
return root->val < limit ? NULL : root;
if (root->left)
root->left = sufficientSubset(root->left, limit - root->val);
if (root->right)
root->right = sufficientSubset(root->right, limit - root->val);
return root->left == root->right ? NULL : root;
}
};