【LeetCode】814. Binary Tree Pruning 解題報告(Python)__Python

來源:互聯網
上載者:User
【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 日 ———— 網吧通宵了,然後睡了一天。。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.