Skip to content

Commit e15492b

Browse files
author
dbcai
committed
添加 前序.ACM模式如何构建二叉树.md Java版本
1 parent 1d6f2c9 commit e15492b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

problems/前序/ACM模式如何构建二叉树.md

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,59 @@ int main() {
217217
## Java
218218

219219
```Java
220+
public class Solution {
221+
// 节点类
222+
static class TreeNode {
223+
// 节点值
224+
int val;
225+
226+
// 左节点
227+
TreeNode left;
228+
229+
// 右节点
230+
TreeNode right;
231+
232+
// 节点的构造函数(默认左右节点都为null)
233+
public TreeNode(int x) {
234+
this.val = x;
235+
this.left = null;
236+
this.right = null;
237+
}
238+
}
239+
240+
/**
241+
* 根据数组构建二叉树
242+
* @param arr 树的数组表示
243+
* @return 构建成功后树的根节点
244+
*/
245+
public TreeNode constructBinaryTree(final int[] arr) {
246+
// 构建和原数组相同的树节点列表
247+
List<TreeNode> treeNodeList = arr.length > 0 ? new ArrayList<>(arr.length) : null;
248+
TreeNode root = null;
249+
// 把输入数值数组,先转化为二叉树节点列表
250+
for (int i = 0; i < arr.length; i++) {
251+
TreeNode node = null;
252+
if (arr[i] != -1) { // 用 -1 表示null
253+
node = new TreeNode(arr[i]);
254+
}
255+
treeNodeList.add(node);
256+
if (i == 0) {
257+
root = node;
258+
}
259+
}
260+
// 遍历一遍,根据规则左右孩子赋值就可以了
261+
// 注意这里 结束规则是 i * 2 + 2 < arr.length,避免空指针
262+
for (int i = 0; i * 2 + 2 < arr.length; i++) {
263+
TreeNode node = treeNodeList.get(i);
264+
if (node != null) {
265+
// 线性存储转连式存储关键逻辑
266+
node.left = treeNodeList.get(2 * i + 1);
267+
node.right = treeNodeList.get(2 * i + 2);
268+
}
269+
}
270+
return root;
271+
}
272+
}
220273
```
221274

222275

0 commit comments

Comments
 (0)