From d4d3dc03a9fdf96f96f4feb0f1ff3487ff53573f Mon Sep 17 00:00:00 2001 From: Nezuko-Wen <409053122@qq.com> Date: Sat, 5 Dec 2020 11:39:14 +0800 Subject: [PATCH] =?UTF-8?q?dfs=E6=89=BE=E5=A5=BD=E5=8F=B6=E5=AD=90?= =?UTF-8?q?=E8=8A=82=E7=82=B9=E5=AF=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leecode/tree/No1530.java | 52 ++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 src/leecode/tree/No1530.java diff --git a/src/leecode/tree/No1530.java b/src/leecode/tree/No1530.java new file mode 100644 index 0000000..484287e --- /dev/null +++ b/src/leecode/tree/No1530.java @@ -0,0 +1,52 @@ +package leecode.tree; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * 给你二叉树的根节点 root 和一个整数 distance 。 + * + * 如果二叉树中两个 叶 节点之间的 最短路径长度 小于或者等于 distance ,那它们就可以构成一组 好叶子节点对 。 + * + * 返回树中 好叶子节点对的数量 + * + * 来源:力扣(LeetCode) + * 链接:https://leetcode-cn.com/problems/number-of-good-leaf-nodes-pairs + */ +public class No1530 { + private int ret = 0; + + public int countPairs(TreeNode root, int distance) { + dfs(root, distance); + return ret; + } + + private List dfs(TreeNode root, int distance) { + if (root == null) return null; + if (root.left == null && root.right == null) return Collections.singletonList(0); + List dfsOnce = new ArrayList<>(); + List leftArr = dfs(root.left, distance); + List rightArr = dfs(root.right, distance); + if (root.left != null) { + for (int l : leftArr) { + if (++l > distance) continue; + dfsOnce.add(l); + } + } + if (root.right != null) { + for (int r : rightArr) { + if (++r > distance) continue; + dfsOnce.add(r); + } + } + if (root.left != null && root.right != null) { + for (int l : leftArr) { + for (int r : rightArr) { + if (l + r + 2 <= distance) ret++; + } + } + } + return dfsOnce; + } +}