"Leetcode" 814. Binary Tree Pruning problem-solving report (Python)
tags (space-delimited): Leetcode
Topic Address: https://leetcode.com/problems/binary-tree-pruning/description/ topic Description:
We are given the head node root of a binary, where additionally every node ' s value is either a 0 or a 1.
Return to the same tree where every subtree (of the given tree) is not containing a 1 has been.
(Recall that the subtree of a node x are 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 "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'll have at most nodes. The value of each node is 0 or 1. The main effect of the topic
Remove all but 1 subtree of a tree. methods of Solving problems
This question or Dfs ah ~ accustomed to a new definition of a function DFS, but this time no need. We'll just have to reset the node's left and right children.
It is important to note that we determine that this node is a leaf node and that the node value is 1 after the left and right subtree is processed. Can be seen from the Example2, if the 0 nodes are 0 nodes, then the left and right nodes are subtracted, but also to determine whether they are 0, and then cut themselves.
# Definition for a binary tree node.
# class TreeNode (object):
# def __init__ (self, x):
# self.val = x
# self.left = None
# self.right = None
class 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
Date
April 8, 2018 ———— Internet cafes all night, and then sleep for a day.