leetcode 814. Binary Tree Pruning
原题地址:https://leetcode.com/problems/binary-tree-pruning/
题目
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.
python代码1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
root1 = TreeNode(0)
def pruneTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root is not None:
self.root1 = root
def ok(node, node1):
if node == None:
node1 = None
else:
node1.val = node.val
if self.hasOne(node.left):
node1.left = node.left
ok(node.left, node1.left)
ok(node.right, node1.right)
else:
node1.left = None
if self.hasOne(node.right):
node1.right = node.right
ok(node.left, node1.left)
ok(node.right, node1.right)
else:
node1.right = None
ok(root, self.root1)
return self.root1
def hasOne(self, node):
if node is None:
return False
if node.val == 1:
return True
elif node.val == 0:
return self.hasOne(node.left) or self.hasOne(node.right)
python代码2
def pruneTree(self, root):
if not root: return None
root.left = self.pruneTree(root.left)
root.right = self.pruneTree(root.right)
if not root.left and not root.right and not root.val: return None
return root
版权声明:转载注明 http://blog.csdn.net/birdreamer/article/details/79850009