后续补充:
存在疑问:
1)数组只能构建完全二叉树吗?可否使用{1,2,null,1,2,3,...}的形式构建非完全二叉树
部分代码参考自leetcode中的思想 104. 二叉树的最大深度
import java.util.ArrayList;
import java.util.List;
public class BinTree {
private int array[] = {3,9,20, 1, 2,15,7};
private static List<Node> nodeLIst = new ArrayList<Node>();
private static class Node {
Node left;
Node right;
int data;
Node(int data) {
this.data = data;
}
}
public void createBintree() {
for (int i = 0; i < array.length; i++) {
nodeLIst.add(new Node(array[i]));
}
if (nodeLIst.size() > 0) {
for (int y = 0; y < array.length / 2 - 1; y++) {
//leftChild
if (null != nodeLIst.get(2 * y + 1)) {
nodeLIst.get(y).left = nodeLIst.get(2 * y + 1);
}
//rightChild
if (null != nodeLIst.get(2 * y + 2)) {
nodeLIst.get(y).right = nodeLIst.get(2 * y + 2);
}
}
//最后一个父节点不一定有孩子
int lastParentIndex = array.length / 2 - 1;
// 左孩子
nodeLIst.get(lastParentIndex).left = nodeLIst
.get(lastParentIndex * 2 + 1);
//奇数时候有右孩子
if (array.length % 2 == 1) {
nodeLIst.get(lastParentIndex).right = nodeLIst
.get(lastParentIndex * 2 + 2);
}
}
}
/**
* 先序遍历
*
* @param node
*/
/* public static void preOrderTraver(Node node) {
if (null != node) {
System.out.println("node:" + node.data);
preOrderTraver(node.leftChild);
preOrderTraver(node.rightChidl);
} else {
return;
}
}*/
public static void main(String[] args) {
BinTree tree = new BinTree();
tree.createBintree();
System.out.println(maxDepth(nodeLIst.get(0)));
//preOrderTraver(nodeLIst.get(0));
}
static int maxDepth(Node node) {
if(node==null){
return 0;
}
else if(node.left==null&& node.right==null){
return 1;
}
else{
int left=maxDepth(node.left);
int right= maxDepth(node.right);
return (left>right? left+1:right+1);
}
}
}