二叉树的数据结构就是一个个结点,节点内部有指向左右子结点。
@Data
public class Node {
private Object data;
private Node leftChild;
private Node rightChild;
public Node(Object data) {
this.data = data;
}
public Node(Object data, Node leftChild, Node rightChild) {
this.data = data;
this.leftChild = leftChild;
this.rightChild = rightChild;
}
@Override
public String toString() {
return "Node{" +
"data=" + data +
", leftChild=" + leftChild +
", rightChild=" + rightChild +
'}';
}
}
二叉树通过递归实现先序,中序和后序排列
public class BinaryTreeImpl implements BinaryTree {
private Node root;
public BinaryTreeImpl(Node root) {
this.root = root;
}
@Override
public boolean isEmpty() {
return null == root;
}
@Override
public int size() {
return size(root);
}
private int size(Node node) {
if (null != node) {
int ls = size(node.getLeftChild());
int rs = size(node.getRightChild());
return ls + rs + 1;
} else {
return 0;
}
}
@Override
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (null != node) {
int ls = getHeight(node.getLeftChild());
int rs = getHeight(node.getRightChild());
return ls > rs ? ls + 1 : rs + 1;
} else {
return 0;
}
}
@Override
public Node findKey(Node node) {
return findKey(node, root);
}
private Node findKey(Node node, Node root) {
if (null != root) {
if (root.getData() == node.getData()) {
return root;
}
Node result = findKey(node, root.getLeftChild());
if (null != result) {
return result;
}
result = findKey(node, root.getRightChild());
if (null != result) {
return result;
}
}
return null;
}
@Override
public void preOrderTraverse() {
System.out.println("Start preOrderTraverse");
preOrderTraverse(root);
}
private void preOrderTraverse(Node node) {
if (node != null) {
System.out.print(node.getData() + " ");
preOrderTraverse(node.getLeftChild());
preOrderTraverse(node.getRightChild());
}
}
@Override
public void postOrderTraverse() {
System.out.println("Start postOrderTraverse");
postOrderTraverse(root);
}
private void postOrderTraverse(Node node) {
if (node != null) {
postOrderTraverse(node.getLeftChild());
postOrderTraverse(node.getRightChild());
System.out.print(node.getData() + " ");
}
}
@Override
public void innerOrderTraverse() {
System.out.println("Start innerOrderTraverse");
innerOrderTraverse(root);
}
private void innerOrderTraverse(Node node) {
if (node != null) {
innerOrderTraverse(node.getLeftChild());
System.out.print(node.getData() + " ");
innerOrderTraverse(node.getRightChild());
}
}
}
网友评论