814. Binary Tree Pruning 二元樹修剪
❀ Origin
Problem
We 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.)
Example 1
1 | Input: [1,null,0,0,1] |
Example 2
1 | Input: [1,0,1,0,0,0,1] |
Example 3
1 | Input: [1,1,0,1,1,0,1,0] |
Note
- The binary tree will have at most 100 nodes.
- The value of each node will only be 0 or 1.
❀ 翻譯
問題
我們被給予一個二元樹的頭根節點, 另外每個節點的值只會 0 或是 1 .
回傳一樣的樹, 但所有不包含 1 的子樹(在被給定的樹)都已經被移除的一樣那棵樹.
(回想一下, 節點 X 的子樹是 X , 加上每一個節點都是 X 的後代)
注意
- 該二元樹最多只有 100 個節點.
- 每一個節點的值不是 0 就是 1 .
❀ Solution
Idea
- 用 遞迴 進到每一個節點
- 判斷是不是其 root.val 是不是 0 , 是的話就給予 null
JavaScript
1 | /** |
Execution
1 | Input: [1,0,1,0,0,0,1] |