二叉树遍历分为三种先序遍历
- 首先访问根,再先序遍历左子树,最后先序遍历右子树 根 --> 左 – > 右
- 无序中序遍历首先中序遍历左子树,再访问根,最后中序遍历右子树 左 --> 根 --.> 右
- 升序后序遍历首先后序遍历左子树,再后序遍历右子树,最后访问根 左 --> 右 --> 跟 左–>根–>右排序
实现:
public class BinaryTree {
private Node root;//节点
//添加节点
public void add(int data) {
if(root == null) {
root = new Node(data);
}else {
root.addNode(data);
}
}
public void printBinaryTree() {
root.print();
}
class Node{
private int data;//数据
private Node left; //左
private Node right; //右
public Node(int data) {
this.data = data;
}
//添加节点(左/右)
public void addNode(int data) {
if(this.data > data) {
if(this.left == null) {
this.left = new Node(data);
}else {
//递归
this.left.addNode(data);
}
}else {
if(this.right == null) {
this.right = new Node(data);
}else {
this.right.addNode(data);
}
}
}
//左 --> 根 ---> 右
public void print() {
if(this.left != null) {
this.left.print();
}
System.out.print(this.data+"->");
if(this.right != null) {
this.right.print();
}
}
}
}
public class Test {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(3);
bt.add(10);
bt.add(6);
bt.add(7);
bt.add(14);
bt.add(13);
bt.add(2);
bt.printBinaryTree();
}
}