Java二叉树的遍历

package com.neu.util;
public class Node { 
     private Node left;   //左节点
     private Node right;  //右节点
     private int data;
    
     public Node(int data) {
this.data=data;
}

public Node getLeft() {
return left;
}

public void setLeft(Node left) {
this.left = left;
}

public Node getRight() {
return right;
}

public void setRight(Node right) {
this.right = right;
}

public int getData() {
return data;
}

public void setData(int data) {
this.data = data;
}
}



package com.neu.util;

public class MyBinaryTree {
private static Node root;  //根节点

public static Node getRoot() {
return root;
}

public void setRoot(Node root) {
this.root = root;
}

public MyBinaryTree(Node r) {
this.root = r;
}

public void addData(int n) {   //创建树
if (root == null) {
root = new Node(n);
} else {
boolean flag = true;
Node parent = root;
Node insertNode = new Node(n);
while (flag) {  //死循环,直到节点插入到正确位置或元素已存在
if (n <= parent.getData()) {
if (parent.getLeft() == null) {//如果没有左子节点,则或把新增元素设置成左子节点
parent.setLeft(insertNode);
flag = false;
} else {
parent = parent.getLeft();  //如果左子树不为空,则还要继续找添加点
}
} else if (n > parent.getData()) {
if (parent.getRight() == null) {//如果没有右子节点,则或把新增元素设置成右子节点    
parent.setRight(insertNode);
flag = false;
} else {
parent = parent.getLeft();  //如果右子树不为空,则还要继续找添加点
}
}
}
}
}

public static void visit(Node p) {
System.out.print(p.getData() + " ");
}

public static void preorder(Node p){  //前序排列
if (p != null) {  
visit(p);
preorder(p.getLeft());
    preorder(p.getRight());
        }
}

protected static void inorder(Node p) { //中序排序
if (p != null) { 
     inorder(p.getLeft()); 
     visit(p); 
     inorder(p.getRight()); 
    } 


  protected static void postorder(Node p) {  //后序排列
  if (p != null) { 
      postorder(p.getLeft()); 
      postorder(p.getRight()); 
      visit(p); 
      } 


public static void main(String[] args) {
Node node = new Node(10);
MyBinaryTree bt = new MyBinaryTree(node);
bt.addData(5);
bt.addData(12);
bt.addData(20);
bt.addData(2);
bt.addData(14);
bt.addData(1);
preorder(MyBinaryTree.getRoot());
System.out.println();
inorder(MyBinaryTree.getRoot());
System.out.println();
postorder(MyBinaryTree.getRoot());
}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值