none
关于二叉查找树插入新的节点问题? RRS feed

  • 问题

  •     public class Node
        {
            public int Data;
            public Node Left;
            public Node Right;
            public void DisplayNode()
            {
                Console.Write(Data + " ");
            }
        }

        public class BinarySearchTree
        {
            public Node root;
            public BinarySearchTree()
            {
                root = null;
            }
            public void Insert(int i)
            {
                Node newNode = new Node();
                newNode.Data = i;
                if (root == null)
                    root = newNode;
                else
                {
                    Node current = root;
                    Node parent;
                    while (true)
                    {
                        parent = current;
                        if (i < current.Data)
                        {
                            current = current.Left;
                            if (current == null)
                            {
                                parent.Left = newNode;
                                break;
                            }
                        }
                        else
                        {
                            current = current.Right;
                            if (current == null)
                            {
                                parent.Right = newNode;
                                break;
                            }
                        }
                    }
                }
            }
            public void InOrder(Node theRoot)
            {
                if (!(theRoot == null))
                {
                    InOrder(theRoot.Left);
                    theRoot.DisplayNode();
                    InOrder(theRoot.Right);
                }
            }
        }

        class Program
        {
            static void Main(string[] args)
            {
                BinarySearchTree nums = new BinarySearchTree();
                nums.Insert(23);
                nums.Insert(45);
                nums.Insert(16);
                nums.Insert(37);
                nums.Insert(3);
                nums.Insert(99);
                nums.Insert(22);
                Console.WriteLine("Inorder traversal: ");
                nums.InOrder(nums.root);
                Console.WriteLine();

                Console.Read();
            }
        }
    上面黑体部分新值赋值局部变量父节点后是如何将数据更新到root根变量的?


    万物皆变,规则永恒。

    2012年3月19日 3:33

答案

全部回复