leetcode【中等】1325、删除给定值的叶子节点

在这里插入图片描述
思路:递归
左右两个节点遍历完了才考虑中间节点,即后序遍历(左右中)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def removeLeafNodes(self, root: TreeNode, target: int) -> TreeNode:
        if not root:
            return None
        root.left=self.removeLeafNodes(root.left,target)
        root.right=self.removeLeafNodes(root.right,target)
        if not root.left and not root.right and root.val==target: 
            return None
        return root

猜你喜欢

转载自blog.csdn.net/qq_40707462/article/details/114021478