|
51 | 51 |
|
52 | 52 | <!-- 这里可写通用的实现逻辑 -->
|
53 | 53 |
|
| 54 | +递归遍历整棵树,如果到达叶子结点且路径和小于 limit,直接返回 null 表示删除。如果左右子树都被删除,说明经过当前结点的路径和也一定小于 limit,同样需要删除 |
| 55 | + |
54 | 56 | <!-- tabs:start -->
|
55 | 57 |
|
56 | 58 | ### **Python3**
|
57 | 59 |
|
58 | 60 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
59 | 61 |
|
60 | 62 | ```python
|
| 63 | +class Solution: |
| 64 | + def sufficientSubset(self, root: TreeNode, limit: int) -> TreeNode: |
| 65 | + if root is None: |
| 66 | + return None |
| 67 | + |
| 68 | + limit -= root.val |
| 69 | + if root.left is None and root.right is None: |
| 70 | + return None if limit > 0 else root |
| 71 | + |
| 72 | + root.left = self.sufficientSubset(root.left, limit) |
| 73 | + root.right = self.sufficientSubset(root.right, limit) |
61 | 74 |
|
| 75 | + if root.left is None and root.right is None: |
| 76 | + return None |
| 77 | + return root |
62 | 78 | ```
|
63 | 79 |
|
64 | 80 | ### **Java**
|
65 | 81 |
|
66 | 82 | <!-- 这里可写当前语言的特殊实现逻辑 -->
|
67 | 83 |
|
68 | 84 | ```java
|
| 85 | +class Solution { |
| 86 | + public TreeNode sufficientSubset(TreeNode root, int limit) { |
| 87 | + if (root == null) { |
| 88 | + return null; |
| 89 | + } |
| 90 | + limit -= root.val; |
| 91 | + if (root.left == null && root.right == null) { |
| 92 | + return limit > 0 ? null : root; |
| 93 | + } |
| 94 | + root.left = sufficientSubset(root.left, limit); |
| 95 | + root.right = sufficientSubset(root.right, limit); |
| 96 | + return root.left == null && root.right == null ? null : root; |
| 97 | + } |
| 98 | +} |
| 99 | +``` |
| 100 | + |
| 101 | +### **Go** |
| 102 | + |
| 103 | +```go |
| 104 | +func sufficientSubset(root *TreeNode, limit int) *TreeNode { |
| 105 | + if root == nil { |
| 106 | + return nil |
| 107 | + } |
| 108 | + |
| 109 | + limit -= root.Val |
| 110 | + if root.Left == nil && root.Right == nil { |
| 111 | + if limit > 0 { |
| 112 | + return nil |
| 113 | + } |
| 114 | + return root |
| 115 | + } |
| 116 | + |
| 117 | + root.Left = sufficientSubset(root.Left, limit) |
| 118 | + root.Right = sufficientSubset(root.Right, limit) |
| 119 | + |
| 120 | + if root.Left == nil && root.Right == nil { |
| 121 | + return nil |
| 122 | + } |
| 123 | + return root |
| 124 | +} |
| 125 | +``` |
| 126 | + |
| 127 | +### **C++** |
| 128 | + |
| 129 | +```cpp |
| 130 | +class Solution { |
| 131 | +public: |
| 132 | + TreeNode* sufficientSubset(TreeNode* root, int limit) { |
| 133 | + if (root == nullptr) return nullptr; |
| 134 | + |
| 135 | + limit -= root->val; |
| 136 | + if (root->left == nullptr && root->right == nullptr) |
| 137 | + return limit > 0 ? nullptr : root; |
| 138 | + |
| 139 | + root->left = sufficientSubset(root->left, limit); |
| 140 | + root->right = sufficientSubset(root->right, limit); |
69 | 141 |
|
| 142 | + if (root->left == nullptr && root->right == nullptr) |
| 143 | + return nullptr; |
| 144 | + return root; |
| 145 | + } |
| 146 | +}; |
70 | 147 | ```
|
71 | 148 |
|
72 | 149 | ### **...**
|
|
0 commit comments