数据结构 僵尸问题
有1个人和99个僵尸,僵尸吃了人就会恢复成人类,一个人可以让两个僵尸吃,但是被僵尸吃了人就会死掉。问:最后可以活下来的人有多少个?
解:
这个问题可以有二叉树解决,或者的人是二叉树的头,当一个结点有父节点时,父节点一定会被子节点吃掉,也就是只要有子节点的结点,就是被僵尸吃掉的人。如图:
代码如下
代码块
代码块语法遵循标准markdown代码,例如:
package Struture;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class Zombi {
private int[] array = new int[100];
private static List<Node> nodeList1;
private static int count = 0;
private static class Node {
Node leftChild;
Node rightChild;
int data;
Node(int newData) {
leftChild = null;
rightChild = null;
data = newData;
}
}
public void arrayTree() {
for (int i = 0; i < 100; i++) {
array[i] = i + 1;
// System.out.println(array[i]);
}
// System.out.println(array);
}
public void createBinTree2() {
nodeList1 = new LinkedList<Node>();
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
nodeList1.add(new Node(array[nodeIndex]));
}
for (int parentIndex = 0; parentIndex < array.length / 2 - 1; parentIndex++) {
nodeList1.get(parentIndex).leftChild = nodeList1
.get(parentIndex * 2 + 1);
nodeList1.get(parentIndex).rightChild = nodeList1
.get(parentIndex * 2 + 2);
}
int lastParentIndex = array.length / 2 - 1;
nodeList1.get(lastParentIndex).rightChild = nodeList1
.get(lastParentIndex);
if (array.length % 2 == 1) {
nodeList1.get(lastParentIndex).rightChild = nodeList1
.get(lastParentIndex * 2 + 2);
}
}
/**
* 先序遍历 这三种遍历结构都一样,只是先后顺序不一样
*/
public static int preOrderTraverse2(Node node) {
if (node == null) {
return 0;
}
if (node.leftChild == null && node.rightChild == null) {
return 1;
}
System.out.print(node.data + " ");
return preOrderTraverse2(node.leftChild) + preOrderTraverse2(node.rightChild);
}
public static void main(String[] args) {
Zombi tree = new Zombi();
tree.arrayTree();
tree.createBinTree2();
for(int i=0;i<nodeList1.size();i++){
if(nodeList1.get(i).leftChild==null&&nodeList1.get(i).rightChild==null){
System.out.println(nodeList1.get(i).data);
}}}}
结束