From e15492b0b69ca06d8d90057093237de8767bf784 Mon Sep 17 00:00:00 2001 From: dbcai Date: Tue, 26 Apr 2022 22:08:25 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=20=E5=89=8D=E5=BA=8F.ACM?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E5=A6=82=E4=BD=95=E6=9E=84=E5=BB=BA=E4=BA=8C?= =?UTF-8?q?=E5=8F=89=E6=A0=91.md=20Java=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../前序/ACM模式如何构建二叉树.md | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/problems/前序/ACM模式如何构建二叉树.md b/problems/前序/ACM模式如何构建二叉树.md index 28c4b6f7..07674b31 100644 --- a/problems/前序/ACM模式如何构建二叉树.md +++ b/problems/前序/ACM模式如何构建二叉树.md @@ -217,6 +217,59 @@ int main() { ## Java ```Java +public class Solution { + // 节点类 + static class TreeNode { + // 节点值 + int val; + + // 左节点 + TreeNode left; + + // 右节点 + TreeNode right; + + // 节点的构造函数(默认左右节点都为null) + public TreeNode(int x) { + this.val = x; + this.left = null; + this.right = null; + } + } + + /** + * 根据数组构建二叉树 + * @param arr 树的数组表示 + * @return 构建成功后树的根节点 + */ + public TreeNode constructBinaryTree(final int[] arr) { + // 构建和原数组相同的树节点列表 + List treeNodeList = arr.length > 0 ? new ArrayList<>(arr.length) : null; + TreeNode root = null; + // 把输入数值数组,先转化为二叉树节点列表 + for (int i = 0; i < arr.length; i++) { + TreeNode node = null; + if (arr[i] != -1) { // 用 -1 表示null + node = new TreeNode(arr[i]); + } + treeNodeList.add(node); + if (i == 0) { + root = node; + } + } + // 遍历一遍,根据规则左右孩子赋值就可以了 + // 注意这里 结束规则是 i * 2 + 2 < arr.length,避免空指针 + for (int i = 0; i * 2 + 2 < arr.length; i++) { + TreeNode node = treeNodeList.get(i); + if (node != null) { + // 线性存储转连式存储关键逻辑 + node.left = treeNodeList.get(2 * i + 1); + node.right = treeNodeList.get(2 * i + 2); + } + } + return root; + } +} ```