zoukankan      html  css  js  c++  java
  • 数据结构学习--Java遍历二叉树

    一、遍历树

    遍历树是根据一个特定的顺序访问树的每一个节点,根据顺序的不同分为前序、中序、后序遍历三种。

    二、前序遍历

      1、访问根节点

      2、前序遍历左子树

      3、前序遍历右子树

    三、中序遍历

      1、中序遍历左子树

      2、访问根节点

      3、中序遍历右子树

    四、后序遍历

      1、后序遍历左子树

      2、后序遍历右子树

      3、访问根节点

    代码实现

    package com.example.deer;

    public class Tree {
    //根节点
    public Node root;

    /**
    * 插入节点
    * @param value
    */
    public void insert(long value,String sValue){
    //封装节点
    Node newNode = new Node(value,sValue);
    //引用当前节点
    Node current = root;
    //引用父节点
    Node parent;
    //如果root为null,也就是第一次插入的时候
    if(root == null){
    root = newNode;
    return;
    }else{
    while (true){
    //父节点指向当前节点
    parent = current;
    //如果当前指向的节点数据比插入的要大,则向左走
    if(current.data > value){
    current = current.leftChild;
    if(current == null){
    parent.leftChild = newNode;
    return;
    }
    }else{
    current = current.rightChild;
    if(current == null){
    parent.rightChild = newNode;
    return;
    }
    }
    }
    }
    }
    /**
    * 查找节点
    */
    public Node find(long value){
    //引用当前节点,从根节点开始
    Node current = root;
    //循环,只要查找值不等于当前节点的数据项
    while(current.data != value){
    //进行比较,比较查找值和当前节点的大小
    if(current.data > value){
    current = current.leftChild;
    } else {
    current = current.rightChild;
    }
    if(current == null){
    return null;
    }
    }
    return current;
    }

    /**
    * 前序遍历
    */
    public void frontOrder(Node localNode){
    if(localNode != null){
    //访问根节点
    System.out.println(localNode.data + "," + localNode.sData);
    //前序遍历左子树
    frontOrder(localNode.leftChild);
    //前序遍历右子树
    frontOrder(localNode.rightChild);
    }
    }

    /**
    * 中序遍历
    */
    public void inOrder(Node localNode){
    if(localNode != null){
    //中序遍历左子树
    inOrder(localNode.leftChild);
    //访问根节点
    System.out.println(localNode.data + "," + localNode.sData);
    //中序遍历右子树
    inOrder(localNode.rightChild);
    }
    }
    /**
    * 后序遍历
    */
    public void afterOrder(Node localNode){
    if(localNode != null){
    //后序遍历左子树
    afterOrder(localNode.leftChild);
    //后序遍历右子树
    afterOrder(localNode.rightChild);
    //访问根节点
    System.out.println(localNode.data + "," + localNode.sData);
    }
    }
    }
  • 相关阅读:
    vmware虚拟机迁移系统到其它磁盘(xjl456852原创)
    值得思考的
    OS X系统特有文件目录说明
    计算机组成原理语言层级
    PC启动过程详解
    对大学计算机培养方案路线回顾
    Django学习笔记(二)App创建之Model
    Django学习笔记 (一) 开发环境配置
    HTML的发展历史
    如何设置MySql Server远程访问(Debian Linux)
  • 原文地址:https://www.cnblogs.com/xiaohualu/p/11812108.html
Copyright © 2011-2022 走看看