二叉树可以按左边小,右边大,构建
二叉树分左右两个两个指针,分别指向左右两个分支。
其遍历方式可以分为三种:
- 前序遍历:先访问根节点,然后访问左节点,最后右节点
- 中序遍历:先访问左节点,然后访问根节点,最后右节点
- 后续遍历:先访问左节点,然后访问右节点,最后根节点
public class node {
int num;
node left;
node right;
public node(int num){
this.num = num;
this.left = null;
this.right = null;
}
@Override
public String toString() {
return "node{" +
"num=" + num +
'}';
}
}
public class tree {
private node root;
public void setRoot(node root){
this.root = root;
}
// 前序遍历,先输出父节点,在输出左节点-右节点
public void preOrder(node root){
//
if (root==null) return;
System.out.println(root);
preOrder(root.left);
preOrder(root.right);
}
// 中遍历,左节点-父节点-右节点
public void miOrder(node root){
if (root==null) return;
miOrder(root.left);
System.out.println(root);
miOrder(root.right);
}
// 后序遍历,左节点-右节点-父节点
public void laOrder(node root){
if (root==null) return;
laOrder(root.left);
laOrder(root.right);
System.out.println(root);
}
public static void main(String[] args) {
// 手动建立树
node node1 = new node(1);
node node2 = new node(2);
node node3 = new node(3);
node node4 = new node(4);
node node5 = new node(5);
tree myTree = new tree();
myTree.setRoot(node1);
node1.left = node2;
node1.right = node3;
node3.right = node4;
node3.left = node5;
// 测试各个遍历函数
System.out.println("previous");
myTree.preOrder(myTree.root);
System.out.println("middle");
myTree.miOrder(myTree.root);
System.out.println("last");
myTree.laOrder(myTree.root);
}
}