https://github.com/emahtab/binary-tree-pruning
Binary Tree Pruning
https://github.com/emahtab/binary-tree-pruning
binary-tree leetcode problem-solving pruning
Last synced: 4 months ago
JSON representation
Binary Tree Pruning
- Host: GitHub
- URL: https://github.com/emahtab/binary-tree-pruning
- Owner: eMahtab
- Created: 2020-02-02T12:33:10.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-03-11T17:55:24.000Z (over 5 years ago)
- Last Synced: 2025-02-02T03:26:16.477Z (9 months ago)
- Topics: binary-tree, leetcode, problem-solving, pruning
- Homepage:
- Size: 23.4 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Binary Tree Pruning
## https://leetcode.com/problems/binary-tree-pruningWe are given the head node root of a binary tree, where additionally every node's value is either a 0 or a 1.
Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
(Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
**Note:**
1. The binary tree will have at most 100 nodes.
2. The value of each node will only be 0 or 1.
# Implementation :
```java
/**
* 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) {
if(root == null)
return null;
return prune(root);
}
public TreeNode prune(TreeNode node){
if(node == null)
return node;
node.left = prune(node.left);
node.right = prune(node.right);
return (node.left == null && node.right == null && node.val == 0) ?
null : node;
}
}```
# Key Points :
Note that in the recursive prune method we are first calling the prune on left subtree and right subtree, if we move the check `(node.val == 0 && node.left == null && node.right == null)` before calling prune on left subtree and right subtree, it will lead to wrong result.# References :
https://www.youtube.com/watch?v=77LJc56bwnE