leetcode814 Binary Tree Pruning

Posted yawenw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode814 Binary Tree Pruning相关的知识,希望对你有一定的参考价值。

 1 """
 2 We are given the head node root of a binary tree, where additionally every node‘s value is either a 0 or a 1.
 3 Return the same tree where every subtree (of the given tree) not containing a 1 has been removed.
 4 (Recall that the subtree of a node X is X, plus every node that is a descendant of X.)
 5 Example 1:
 6 Input: [1,null,0,0,1]
 7 Output: [1,null,0,null,1]
 8 Explanation:
 9 Only the red nodes satisfy the property "every subtree not containing a 1".
10 The diagram on the right represents the answer.
11 Example 2:
12 Input: [1,0,1,0,0,0,1]
13 Output: [1,null,1,null,1]
14 Example 3:
15 Input: [1,1,0,1,1,0,1,0]
16 Output: [1,1,0,1,1,null,1]
17 """
18 """
19 剪枝问题:
20 递归遍历,不用考虑递归左右顺序
21 如果结点值为0且,左右孩子为None
22 将该结点置为None
23 """
24 class TreeNode:
25     def __init__(self, x):
26         self.val = x
27         self.left = None
28         self.right = None
29 
30 class Solution:
31     def pruneTree(self, root):
32         if root == None:
33             return None
34         root.left = self.pruneTree(root.left)
35         root.right = self.pruneTree(root.right)
36         if root.val == 0 and root.left == None and root.right == None: #!!!判别式
37             return None
38         return root

 

以上是关于leetcode814 Binary Tree Pruning的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 814. Binary Tree Pruning

leetcode814 Binary Tree Pruning

Leetcode 814. 二叉树剪枝

Leetcode 之Binary Tree Preorder Traversal(42)

257. Binary Tree Paths

109. Convert Sorted List to Binary Search Tree