You are given the root of a binary tree and an integer distance. A pair of two different leaf nodes of a binary tree is said to be good if the length of the shortest path between them is less than or equal to distance.
Return the number of good leaf node pairs in the tree.
Example 1:
Input: root = [1,2,3,null,4], distance = 3
Output: 1
Explanation: The leaf nodes of the tree are 3 and 4 and the length of the shortest path between them is 3. This is the only good pair.
Example 2:
Input: root = [1,2,3,4,5,6,7], distance = 3
Output: 2
Explanation: The good pairs are [4,5] and [6,7] with shortest path = 2. The pair [4,6] is not good because the length of ther shortest path between them is 4.
Example 3:
Input: root = [7,1,4,6,null,5,3,null,null,null,null,null,2], distance = 3
Output: 1
Explanation: The only good pair is [2,5].
Constraints:
The number of nodes in the tree is in the range [1, 210].
1 <= Node.val <= 100
1 <= distance <= 10
Solutions
Solution 1: Recursion
The problem asks for the number of good leaf node pairs in a binary tree. The answer can be divided into three parts: the number of good leaf node pairs in the left subtree, the number of good leaf node pairs in the right subtree, and the number of good leaf node pairs formed by leaf nodes from the left subtree and leaf nodes from the right subtree.
We can solve this recursively.
The time complexity is \(O(n \times d^2 \times h)\), where \(n\) is the number of nodes in the binary tree, and \(h\) and \(d\) are the height of the binary tree and the distance limit, respectively. The space complexity is \(O(h)\) for the recursion stack.
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funccountPairs(root*TreeNode,distanceint)int{ifroot==nil{return0}ans:=countPairs(root.Left,distance)+countPairs(root.Right,distance)cnt1:=make([]int,distance)cnt2:=make([]int,distance)dfs(root.Left,cnt1,1)dfs(root.Right,cnt2,1)fori,v1:=rangecnt1{forj,v2:=rangecnt2{ifi+j<=distance{ans+=v1*v2}}}returnans}funcdfs(root*TreeNode,cnt[]int,iint){ifroot==nil||i>=len(cnt){return}ifroot.Left==nil&&root.Right==nil{cnt[i]++return}dfs(root.Left,cnt,i+1)dfs(root.Right,cnt,i+1)}