leetcode-1530-好叶子结点对的数量

 

 

 

 

 方法:后序遍历

# 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 countPairs(self, root: TreeNode, distance: int) -> int:
        res = 0
        def dis(root):
            nonlocal res
            if not root:
                return []
            if not root.left and not root.right:
                return [1]
            l, r = dis(root.left), dis(root.right)
            for i in l:
                for j in r:
                    if i + j <= distance:
                        res += 1
            dep = [i + 1 for i in l + r]  # 记录该点到所有叶子结点的距离
            return dep
        dis(root)
        return res

 

posted @ 2020-08-01 09:15  oldby  阅读(256)  评论(0编辑  收藏  举报