码迷,mamicode.com
首页 > 编程语言 > 详细

(C# Binary Tree) 基本概念和算法

时间:2015-11-20 17:35:58      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:

A binary tree is defined as a tree where each node can have no more than two children.

Building a Binary Search Tree:

首先创建一个节点Class

    public class BtNode
    {
        public int Data { get; set; }

        public BtNode Left { get; set; }

        public BtNode Right { get; set; }

        public void DisplayNode()
        {
            Console.Write("Data: {0}, ", this.Data); 
        }
    }

然后创建BST Class 提供Insert 方法:

    public class BinarySearchTree
    {
        private BtNode root = null; 

        public void Insert(int data)
        {
            BtNode newNode = new BtNode(); 
            if (this.root == null)
            {
                this.root = newNode; 
            }
            else
            {
                // Add to children nodes.
                BtNode current = new BtNode();
                BtNode parent = new BtNode(); 

                while(true)
                {
                    parent = current; 
                    if (data < current.Data)
                    {
                        current = current.Left; 
                        if (current == null )
                        {
                            parent.Left = newNode; 
                            break; 
                        }
                        
                    }
                    else
                    {
                        current = current.Right; 
                        if (current == null)
                        {
                            parent.Right = newNode;
                            break; 
                        }
                    }
                }
            }
        }
    }

 

(C# Binary Tree) 基本概念和算法

标签:

原文地址:http://www.cnblogs.com/fdyang/p/4981175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!