java 树 广度优先遍历_JAVA实现树结构的深度和广度优先遍历

String value;

List children = new ArrayList();

public Node(String value){

this.value = value;

}

public static void main(String[] args) {

Node root = new Node("A");

root.children.add(new Node("B"));

root.children.add(new Node("C"));

root.children.get(1).children.add(new Node("C1"));

root.children.get(1).children.get(0).children.add(new Node("C11"));

root.children.get(1).children.get(0).children.add(new Node("C12"));

root.children.get(1).children.add(new Node("C2"));

root.children.add(new Node("D"));

root.children.get(2).children.add(new Node("D1"));

root.children.get(2).children.add(new Node("D2"));

// 上面是初始化数据,结构是这样的:

/**

* A

* B

* C

* C1

* C11

* C12

* C2

* D

* D1

* D2

*/

System.out.println("深度优先");

print(root);

System.out.println("-----------------------");

System.out.println("广度优先");

print2(root, root, 1);

}

/**

* 深度优先

*

* @param node

* @param level

*/

static void print(Node node) {

System.out.println(node.value);

if (!node.children.isEmpty()) {

for (Node x : node.children) {

print(x);

}

}

}

/**

* 广度优先

*

* @param root

* @param node

* @param level

*/

static void print2(Node root, Node node, int level) {

if (root == node) {

System.out.println(node.value);

}

print3(root, 1, level);

if (!node.children.isEmpty()) {

for (Node x : node.children) {

print2(root, x, level += 1);

}

}

}

static void print3(Node node, int start, int level) {

List children = node.children;

if (!children.isEmpty()) {

if (start < level) {

for (Node x : children) {

print3(x, start + 1, level);

}

} else {

for (Node x : children) {

System.out.println(x.value);

}

}

}

}

}

输出结果如下:

深度优先

A

B

C

C1

C11

C12

C2

D

D1

D2

-----------------------

广度优先

A

B

C

D

C1

C2

D1

D2

C11

C12

写了一个感觉更好的广度优先实现:

把上面main()中的print2(xxx)换成print5(root);

/**

* 广度优先 —— 法2

*

* @param node

*/

static void print5(Node node) {

List list = node.children;

do {

for (Node x : list) {

System.out.println(x.value);

}

list = getNextLevelNode(list);

} while (list != null);

}

static List getNextLevelNode(List nodeList) {

if (!nodeList.isEmpty()) {

List list = new ArrayList();

for (Node node : nodeList) {

list.addAll(node.children);

}

return list;

}

return null;

}

输出结果一样:

-----------------------

广度优先

B

C

D

C1

C2

D1

D2

C11

C12

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值