现在的位置: 首页 > 综合 > 正文

二叉树排序法

2013年12月01日 ⁄ 综合 ⁄ 共 2540字 ⁄ 字号 评论关闭
 

/*刘强
  *目标:实现不规律的一组数据进行排序(二叉树)。
  */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BinaryTree
{
    sealed class BinaryTreeClass
    {
        sealed class TreeNode
        {
            private int _nodevalue;
            private TreeNode _leftnode;
            private TreeNode _rightnode;
            public TreeNode(int nodevalue)
            {
                this._nodevalue = nodevalue;
                this._leftnode = null;
                this._rightnode = null;
            }
            public int NodeValue
            {
                get { return this._nodevalue; }
            }
            public TreeNode LeftNode
            {
                get { return this._leftnode; }
                set { this._leftnode = value; }
            }
            public TreeNode RightNode
            {
                get { return this._rightnode; }
                set { this._rightnode = value; }
            }
 
        }
        private TreeNode _rootnode;

        public void AddNum(int num)
        {
            TreeNode node = new TreeNode(num);
            //子方法
            this.addnode(node,this._rootnode);

        }
        private void addnode(TreeNode node,TreeNode cursorNode)
        {
            if (cursorNode == null)
            {
                this._rootnode = node;
            }
            else
            {
                if (cursorNode.NodeValue >= node.NodeValue)//左边
                {
                    if (cursorNode.LeftNode == null)//如果左边为空,则添 加上
                    {
                        cursorNode.LeftNode = node;
                    }
                    else
                    {
                        this.addnode(node,cursorNode.LeftNode);//继续递 归
                    }
                   
                }
                else//右边
                {
                    if (cursorNode.RightNode == null)//如果右边边为空, 则添加上
                    {
                        cursorNode.RightNode = node;
                    }
                    else
                    {
                        this.addnode(node,cursorNode.RightNode);//继续递 归
                    }
 
                }
 
            }
 
        }

        //binarytree中序遍历
        public List<int> GetList()
        {
            List<int> list = new List<int>();
            //方法
            this.fullList(list,this._rootnode);
            return list;
         }
        private void fullList(List<int> list,TreeNode cursornode )
        {
            if (cursornode == null)
            {
                //nothing to do here!
            }
            else
            {
                this.fullList(list,cursornode.LeftNode);
                list.Add(cursornode.NodeValue );
                this.fullList(list, cursornode.RightNode);
            }
 
        }
    }

}

 

抱歉!评论已关闭.