zoukankan      html  css  js  c++  java
  • 十九、二叉树的遍历

    原理图:

    理论值:

         前序遍历:10 5 3 6 20 15 30

         中序遍历:3 5 6 10 15 20 30

         后序遍历:3 6 5 15 30 20 10

    运行结果:

    源代码:

    Node参见上一节,这里就不装逼了。

    Tree:

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

    public void insert(int value,String name) //插入结点
    {
    //封装成结点
    Node newNode = new Node(value,name);
    //引用当前结点
    Node current = root;
    //引用父结点
    Node parent;
    //判断是否为空树
    if(current == 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(int 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.print(localNode.data + "," + localNode.name+" "); //打印根
    frontOrder(localNode.leftChild); //左子树
    frontOrder(localNode.rightChild); //右子树
    }

    }

    /*中序遍历*/
    public void inOrder(Node localNode)
    {
    if(localNode != null)
    {
    inOrder(localNode.leftChild); //中序遍历左子树
    System.out.print(localNode.data + "," + localNode.name+" "); //打印根
    inOrder(localNode.rightChild); //遍历右子树
    }
    }

    /*后序遍历*/
    public void lastOrder(Node localNode)
    {
    if(localNode != null)
    {
    lastOrder(localNode.leftChild); //后序遍历左子树
    lastOrder(localNode.rightChild); //后序遍历右子树
    System.out.print(localNode.data + "," + localNode.name+" "); //打印根
    }
    }


    }

  • 相关阅读:
    POJ 2411 状态压缩递,覆盖方案数
    POJ 2774 最长公共子串
    POJ 1743 不可重叠的最长重复子串
    POJ 3294 出现在至少K个字符串中的子串
    POJ 3261 出现至少K次的可重叠最长子串
    POJ 1741/1987 树的点分治
    HDU1556 Color the ball
    解决linux系统时间不对的问题
    CentOS 6.9使用Setup配置网络(解决dhcp模式插入网线不自动获取IP的问题)
    Linux网络配置(setup)
  • 原文地址:https://www.cnblogs.com/fyz666/p/8513086.html
Copyright © 2011-2022 走看看