File tree Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Expand file tree Collapse file tree 3 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ ---
2+ title : " [Leetcode] 814. Binary Tree Pruning explained"
3+ excerpt : " Leetcode daily challenge 2022 september 6th solution"
4+ header :
5+ overlay_image : /public/images/problem-solving-common-header.png
6+ tags :
7+ - Tree
8+ - Postorder traversal
9+ - Recursion
10+ last_modified_at : 2022-09-06T13:11:08+09:00
11+ ---
12+
13+ <a href =" https://leetcode.com/ " >
14+ <img src="/public/images/leetcode-logo.jpeg"/>
15+ </a >
16+
17+ ## Problem
18+
19+ <a href =" https://leetcode.com/problems/binary-tree-pruning/ " >
20+ <img src="/public/images/leetcode-814.png"/>
21+ </a >
22+
23+ <br />
24+
25+ ## Key Idea
26+
27+ For each tree node, repeat below process.
28+
29+ 1 . Prune left child.
30+ 2 . Prune right child.
31+ 3 . If left and right child is ` null ` and this node doesn't have value ` 1 ` , return ` null ` (prunning).
32+
33+ - Time: $$ O(n) $$
34+ - Space: $$ O(n) $$
35+
36+ <br />
37+
38+ ## Implementation
39+
40+ <img src =" /public/images/leetcode-814-result.png " />
41+
42+ ``` java
43+ /**
44+ * author: jooncco
45+ * written: 2022. 9. 6. Tue. 13:14:14 [UTC+9]
46+ **/
47+
48+ class Solution {
49+ private final int TARGET_VALUE = 1 ;
50+
51+ public TreeNode pruneTree (TreeNode root ) {
52+ if (root == null ) return null ;
53+
54+ root. left= pruneTree(root. left);
55+ root. right= pruneTree(root. right);
56+ if (root. left == null && root. right == null && root. val != TARGET_VALUE ) return null ;
57+ return root;
58+ }
59+ }
60+ ```
You can’t perform that action at this time.
0 commit comments