forked from varunu28/LeetCode-Java-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary Tree Pruning.java
More file actions
35 lines (30 loc) · 883 Bytes
/
Binary Tree Pruning.java
File metadata and controls
35 lines (30 loc) · 883 Bytes
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
return checker(root);
}
// A checker method which checks every node and makes it null if it doesn't contain a 1
public TreeNode checker(TreeNode root) {
if (!checkForOnes(root)) {
root = null;
return root;
}
root.left = checker(root.left);
root.right = checker(root.right);
return root;
}
// Checks for a 1 in the node
public boolean checkForOnes(TreeNode root) {
if (root == null) return false;
if (root.val == 1) return true;
return checkForOnes(root.left) || checkForOnes(root.right);
}
}