zoukankan      html  css  js  c++  java
  • C#实现二叉树数据结构

    代码
    // Binary Tree的结点类
    class Node
    {
    public int Data { get; set; }
    public Node LeftSubNode { get; set; }
    public Node RightSubNode { get; set; }

    // 结点为自己追加子结点(与向左/向右追加结合,形成递归)
    public void Append(Node subNode)
    {
    if (subNode.Data <= this.Data)
    {
    this.AppendLeft(subNode);
    }
    else
    {
    this.AppendRight(subNode);
    }
    }

    // 向左追加
    public void AppendLeft(Node subNode)
    {
    if (this.LeftSubNode == null)
    {
    this.LeftSubNode = subNode;
    }
    else
    {
    this.LeftSubNode.Append(subNode);
    }
    }

    // 向右追加
    public void AppendRight(Node subNode)
    {
    if (this.RightSubNode == null)
    {
    this.RightSubNode = subNode;
    }
    else
    {
    this.RightSubNode.Append(subNode);
    }
    }

    // 结点显示自己的数据
    public void ShowData()
    {
    Console.WriteLine(
    "Data={0}", this.Data);
    }
    }

    // Binary Tree类
    class Tree
    {
    // 根结点
    public Node Root { get; set; }

    // 以某结点为起点,插入结点
    public void Insert(Node newNode)
    {
    if (this.Root == null)
    {
    this.Root = newNode;
    }
    else
    {
    this.Root.Append(newNode);
    }
    }

    // 重载,默认以根结点为起点插入
    public void MidTravel()
    {
    this.MidTravel(this.Root);
    }

    // 中序遍历(递归)
    public void MidTravel(Node node)
    {
    if (node.LeftSubNode != null)
    {
    this.MidTravel(node.LeftSubNode);
    }

    node.ShowData();

    if (node.RightSubNode != null)
    {
    this.MidTravel(node.RightSubNode);
    }
    }
    }

    class Program
    {
    static void Main(string[] args)
    {
    Tree tree
    = new Tree();

    tree.Insert(
    new Node { Data = 3 });
    tree.Insert(
    new Node { Data = 6 });
    tree.Insert(
    new Node { Data = 2 });
    tree.Insert(
    new Node { Data = 7 });
    tree.Insert(
    new Node { Data = 18 });
    tree.Insert(
    new Node { Data = 1 });
    tree.Insert(
    new Node { Data = 2 });
    tree.MidTravel();
    }
    }
  • 相关阅读:
    控制反转和依赖注入
    共识机制是什么?
    实用拜占庭容错算法PBFT
    三种框架对比react vue 和Angular对比
    go语言学习笔记
    激活方法总结
    钱包助记词
    简历中存在的问题的处理
    why we use Symbols in Hash
    compact过滤数组中的nil
  • 原文地址:https://www.cnblogs.com/anyanran/p/binaryTree.html
Copyright © 2011-2022 走看看