I was trying to solve this problem on leetcode, by seeing what i have written i think my logic is correct but i am getting the same tree in return as output which is wrong. I had a doubt can i not set the current scope of root of tree to null ? after seeing the solutions of people they have made the root.left null or root.right null not the root itself like mine.
Am i missing some basic concept here.
Link to the LeetCode problem :- https://leetcode.com/problems/binary-tree-pruning/
My solution :-
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode pruneTree(TreeNode root) {
cleanTree(root);
return root;
}
public boolean cleanTree(TreeNode root) {
if(root == null) {
return true;
}
boolean left = cleanTree(root.left);
boolean right = cleanTree(root.right);
if(root.val == 0 && left && right) {
root = null;
return true;
}
return false;
}
}