转到http://blog.csdn.net/qq_33323162/article/details/78676974
有1个人和99个僵尸,僵尸吃了人就会恢复成人类,一个人可以让两个僵尸吃,但是被僵尸吃了人就会死掉。问:最后可以活下来的人有多少个?
解:
这个问题可以有二叉树解决,活着的人是二叉树的头,当一个结点有父节点时,父节点一定会被子节点吃掉,也就是只要有子节点的结点,就是被僵尸吃掉的人。如图:
1
/ \
1 1
/ \ / \
1 1 1 1
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;
/**
* 内部类
*
* @author SONY
*
*/
private static class Node {
Node leftChild;
Node rightChild;
int data;
Node(int newData) {
leftChild = null;
rightChild = null;
data = newData;
}
}
/**
* 用循环做一个100个节点的数组,每个数组元素都为1,这个没什么特殊要求,个人爱好
*/
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 int[] getArray() { return array; } public void setArray(int[]
* array) {
*
* for(int i=0;i<100;i++){ array[i]=i; }
*
* this.array = array; }
*/
/**
* 先序遍历 这三种遍历结构都一样,只是先后顺序不一样
*/
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);
}
}
}
}