您的位置:首页 > 编程语言 > Java开发

java实现二叉树的中序遍历和后续遍历

2015-11-28 14:58 435 查看
public class NodeTree {

   String value;

   NodeTree left;

    NodeTree right;

     public NodeTree(String value, NodeTree left, NodeTree right) {

  this.value = value;

  this.left = left;

  this.right = right;

  }

     

     

}

public class MidTreeSearch {

public static void main(String[] args) {
// TODO Auto-generated method stub
NodeTree root = creatTree();
LookMid(root);
NodeTree aim=LookElement(root, "C");
if(aim.left!=null)
{
System.out.println(aim.left.value+"===");
}
}

//创建二叉树
/*

*     A

*   B     C

* D   G  L   F

*   K   M
*/
public static NodeTree creatTree() {
NodeTree root = null;
NodeTree K = new NodeTree("K", null, null);
NodeTree L = new NodeTree("L", null, null);
NodeTree M = new NodeTree("M", null, null);
NodeTree G = new NodeTree("G", null, M);
NodeTree D = new NodeTree("D", null, K);
NodeTree F = new NodeTree("F", null, null);
NodeTree B = new NodeTree("B", D, G);
NodeTree C = new NodeTree("C", L, F);
NodeTree A = new NodeTree("A", B, C);
root = A;
return root;
}
//中序遍历
public static void LookMid(NodeTree root) {
if (root != null) {
NodeTree nodeLeft=root.left;
LookMid(nodeLeft);
System.out.print(root.value+" ");
NodeTree nodeRight=root.right;
LookMid(nodeRight);
}
}

//后序遍历
public static void LookRear(NodeTree root) {

     if(root!=null)
     {
   
     NodeTree nodeLeft=root.left;
     LookRear(nodeLeft);
     NodeTree nodeRight=root.right;
     LookRear(nodeRight);
     System.out.print(root.value+" ");
     
     }
}

//查找
public static NodeTree LookElement(NodeTree root, String e) {
NodeTree result=null;
if (root != null) {
if (e.equals(root.value)) {
System.out.println("找到了");
result=root;
return result;
} else {
NodeTree nodeLeft = root.left;
result=LookElement(nodeLeft, e);
NodeTree nodeRight = root.right;
result=LookElement(nodeRight, e);
}
}
return result;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: