【LeetCode】814. Binary Tree Pruning 解題報告(Python)
標籤(空格分隔): LeetCode
題目地址:https://leetcode.com/problems/binary-tree-pruning/description/ 題目描述:
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:Input: [1,null,0,0,1]Output: [1,null,0,null,1]
Explanation: Only the red nodes satisfy the property "every subtree not containing a 1".The diagram on the right represents the answer.Example 2:Input: [1,0,1,0,0,0,1]Output: [1,null,1,null,1]
Example 3:Input: [1,1,0,1,1,0,1,0]Output: [1,1,0,1,1,null,1]
Note: The binary tree will have at most 100 nodes. The value of each node will only be 0 or 1. 題目大意
把一棵樹的所有不含1的子樹都刪除。 解題方法
這個題一看還是dfs啊~習慣了新定義一個函數dfs了,但這次不需要了。我們直接把節點的左孩子和右孩子重新設定就好了。
一定要注意的是,我們判斷這個節點是葉子節點並且節點值是1的這個步驟要放在左右子樹處理之後。可以從Example2中看出來,如果0節點的左右子節點都是0,那麼把左右節點都減去了之後,還要判斷自身是不是0,然後把自己也剪了。
# Definition for a binary tree node.# class TreeNode(object):# def __init__(self, x):# self.val = x# self.left = None# self.right = Noneclass Solution(object): def pruneTree(self, root): """ :type root: TreeNode :rtype: TreeNode """ if not root: return root.left = self.pruneTree(root.left) root.right = self.pruneTree(root.right) if not root.left and not root.right and root.val == 0: return None return root
日期
2018 年 4 月 8 日 ———— 網吧通宵了,然後睡了一天。。