通过数组构造二叉树,所有遍历算法以及求二叉树深度的递归算法
[java]
import java.util.LinkedList;
public class BinaryTree {
private Node
private int size; www.2cto.com
public BinaryTree() {
root = new Node
}
public BinaryTree(int[] values) {
System.out.print("新建binaryTree:");
for (int i : values) {
System.out.print(i);
}
System.out.println();
boolean isLeft = true;
int len = values.length;
if (len == 0)
return ;
LinkedList
root = new Node
queue.addLast(root);
Node parent = null;
Node current = null;
for (int i=1; i
queue.addLast(current);
if (isLeft)
parent = queue.getFirst();
else
parent = queue.removeFirst();
if (isLeft) {
parent.setLeftChild(current);
isLeft = false;
}else {
parent.setRightChild(current);
isLeft = true;
}
}
}
public void inorder() {
System.out.print("binaryTree递归中序遍历:");
inorderTraverseRecursion(root);
System.out.println();
}
System.out.print("binaryTree层次遍历:");
LinkedList
queue.addLast(root);
Node
while(!queue.isEmpty()) {
current = queue.removeFirst();
if (current.getLeftChild() != null)
queue.addLast(current.getLeftChild());
if (current.getRightChild() != null)
queue.addLast(current.getRightChild());
System.out.print(current.getValue());
}
System.out.println();
}
public int getLength() {
return getLengthRecursion(root);
}
private int getLengthRecursion(Node
if (node == null)
return 0;
int llen = getLengthRecursion(node.getLeftChild());
int rlen = getLengthRecursion(node.getRightChild());
int maxlen = Math.max(llen, rlen);
return maxlen + 1;
}
public void preorder() {
System.out.print("binaryTree递归先序遍历:");
preorderTraverseRecursion(root);
System.out.println();
}
private void inorderTraverseRecursion(Node
// TODO Auto-generated method stub
if (node.getLeftChild() != null)
inorderTraverseRecursion(node.getLeftChild());
System.out.print(node.getValue());
if (node.getRightChild() != null)
inorderTraverseRecursion(node.getRightChild());
}
private void preorderTraverseRecursion(Node
System.out.print(node.getValue());
if (node.getLeftChild() != null)
preorderTraverseRecursion (node.getLeftChild());
if (node.getRightChild() != null)
preorderTraverseRecursion (node.getRightChild());
}
public void preord