今天用java写数据结构,算是涨姿势了。。。
package leetcode.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
public class MaxSum {
public static void main(String[] args) {
MaxSum ms = new MaxSum();
TreeNode root = ms.initTree();
//ms.printTree(root);
ms.printBroadTree(root);
}
//该方法返回树的头结点
//首先写树的广度优先遍历
public TreeNode initTree(){
TreeNode root = null; //这是根元素
return createNode(root);
}
public TreeNode createNode(TreeNode tn){
int temp;
System.out.print("请输入:");
Scanner scanner = new Scanner(System.in);
temp = scanner.nextInt();
if (temp != 0){
tn = new TreeNode();
tn.value = temp;
tn.lchild = createNode(tn.lchild); //在java中你只能通过参数将一个值传进一个函数,然而你是不能通过参数将一个值带出来的
tn.rchild = createNode(tn.rchild);
return tn;
}else {
tn = null;
return null;
}
}
public void printTree(TreeNode tn){
if (tn != null){
System.out.print(" "+tn.value);
printTree(tn.lchild);
printTree(tn.rchild);
}
}
public void printBroadTree(TreeNode tn){
List<TreeNode> list = new ArrayList<>(); //这个数组用作堆栈
List<TreeNode> removeList = new ArrayList<>(); //这里存储的是要要删除的元素,因为已经访问过
Iterator<TreeNode> iterator;
TreeNode temp = null;
if (tn != null){
list.add(tn);
}
//我感觉下面这句话很关键,如果你要是while(list.size()!=0) ,那么下面有list.add()和list.remove()方法都在改变着list.size()的值
int count = list.size();
while (count != 0){
for (int i=0; i<count; i++){
temp = list.get(i);
System.out.print(temp.value + " ");
removeList.add(temp);
if (temp.lchild != null){
list.add(temp.lchild);
}
if (temp.rchild != null){
list.add(temp.rchild);
}
}
for (int i=0; i<removeList.size(); i++){ //将兄弟节点访问完,一并删除
list.remove(removeList.get(i));
}
count = list.size();
}
}
}