创建一个二叉树对象
private static class Node{
int data;
Node leftNode;
Node righNode;
public Node(int data, Node leftNode, Node righNode) {
super();
this.data = data;
this.leftNode = leftNode;
this.righNode = righNode;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRighNode() {
return righNode;
}
public void setRighNode(Node righNode) {
this.righNode = righNode;
}
}
build 一个二叉树
private static Node rootNode;
public static void buildTree(int[] A){
for(int i:A){
rootNode = insertData(rootNode,i);
}
}
public static void insertData(Node tree, int a){
if (tree == null){
return new Node(a, 0, 0);
}
if (a>tree.getData()){
return tree.setRightNode(insertData(tree.getRightNode(), a));
} else {
return tree.setLeftNode(insertData(tree.getLeftNode(),a));
}
}
遍历
先序遍历
public static void preOrder(Node node){
if (node!=null){
System.out.println(node.getData());
preOrder(node.getLeftNode());
preOrder(node.getRightNode());
}
}
后序遍历
public static void postOrder(Node node){
if (node != null ){
postOrder(node.getLeftNode());
postOrder(node.getRightNode());
System.out.println(node.getData());
}
}
中序遍历
public static void inOrder(Node node){
if (node!=null){
inOrder(node.getLeftNode());
System.out.println(node.getData());
inOrder(node.getRightNode());
}
}
image.png
先序遍历的结果为:0 1 3 7 4 2 5 6
中序遍历的结果为:7 3 1 4 0 5 2 6
后序遍历的结果为:7 3 4 1 5 6 2 0
计算深度
计算深度-递归, 依次计算其左右子树的深度,选其大者
public static int deep(Node node) {
if (node !=null){
int leftDeep= 1, rightDeep=1;
if (node.getLeftNode()!=null)
leftDeep=leftDeep+deep(node.getLeftNode());
if (node.getRightNode() !=null)
rightDeep=rightDeep+deep(node.getRightNode());
return Math.max(leftDeep, rightDeep);
}
}
插入
public Node insert(Node root, int key){
Node newNode =new Node(key,null,null);
Node current = root;
Node parent = null;
if (current == null){
root = newNode;
return newNode;
}
while (true)
{
parent = current;
if (key < current.getData()){
current = current.getLeftNode();
if (current == null)
{
parent.setLeftNode(newNode);
return newNode;
}
}else {
current = current.getRighNode();
if (current ==null){
parent.setRighNode( newNode);
return newNode;
}
}
}
}