二叉树实现-初始化,层序遍历(广搜)

lkpalu Lv3

Java二叉树实现

初始化(满二叉树)

1
2
3
4
5
6
7
8
9
10
public static void FBTreeInit(TreeNode root, int height) {
root.Val = 0;
if (height == 0) {
return;
}
root.Left = new TreeNode(0);
root.Right = new TreeNode(0);
FBTreeInit(root.Left, height - 1);
FBTreeInit(root.Right, height - 1);
}

广度优先搜索

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public static void loTraversal(TreeNode root) {
ArrayList<TreeNode> loTArray = new ArrayList<>();
loTArray.add(root);
while (!loTArray.isEmpty()) {
int length = loTArray.size();
TreeNode node;
for (int i = 0; i < length; i++) {
node = loTArray.removeFirst();
System.out.println(node.Val);
if (node.Left != null) {
loTArray.add(node.Left);
}
if (node.Right != null) {
loTArray.add(node.Right);
}
}
}
}

二叉树类代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package TwoTree;
import java.util.ArrayList;

public class TreeNode {
public int Val;
public TreeNode Left = null;
public TreeNode Right = null;

public TreeNode() {

}

public TreeNode(int val) {
this.Val = val;
}

// height从根节点为0开始
public static void FBTreeInit(TreeNode root, int height) {
root.Val = 0;
if (height == 0) {
return;
}
root.Left = new TreeNode(0);
root.Right = new TreeNode(0);
FBTreeInit(root.Left, height - 1);
FBTreeInit(root.Right, height - 1);
}

public static void loTraversal(TreeNode root) {
ArrayList<TreeNode> loTArray = new ArrayList<>();
loTArray.add(root);
while (!loTArray.isEmpty()) {
int length = loTArray.size();
TreeNode node;
for (int i = 0; i < length; i++) {
node = loTArray.removeFirst();
System.out.println(node.Val);
if (node.Left != null) {
loTArray.add(node.Left);
}
if (node.Right != null) {
loTArray.add(node.Right);
}
}
}
}
}
  • 标题: 二叉树实现-初始化,层序遍历(广搜)
  • 作者: lkpalu
  • 创建于 : 2024-11-03 00:00:00
  • 更新于 : 2024-11-05 17:54:08
  • 链接: https://redefine.ohevan.com/2024/11/03/二叉树实现-初始化,层序遍历(广搜)/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
评论
目录
二叉树实现-初始化,层序遍历(广搜)