自顶向下,判断叶子节点的父节点,如果是将其删除,注意左右子节点有一个是叶子节点即可
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param root TreeNode类
# @return TreeNode类
#
class Solution:
def pruneLeaves(self , root ):
# write code here
def leaf(node):
if not node: return False
return not node.left and not node.right
def check(node):
if not node: return False
if leaf(node.left) or leaf(node.right):
return True
return False
def inOrder(root):
if not root or check(root):
return None
root.left = inOrder(root.left)
root.right = inOrder(root.right)
return root
root = inOrder(root)
return root