How to create a binary tree

前端 未结 5 1151
感情败类
感情败类 2020-12-14 05:17

I did\'nt mean binary search tree.

for example, if I insert values 1,2,3,4,5 in to a binary search tree the inorder traversal will give 1,2,3,4,5 as output.

5条回答
  •  粉色の甜心
    2020-12-14 05:36

      class BstNode
        {
            public int data;
            public BstNode(int data)
            {
                this.data = data;
            }
            public BstNode left;
            public BstNode right;
        }
        class Program
        {
            public static BstNode Insert(BstNode root, int data)
            {
                if (root == null) root = new BstNode(data);
                else if (data <= root.data) root.left = Insert(root.left, data);
                else if (data > root.data) root.right = Insert(root.right, data);
    
                return root;
            }
    
    public static void Main(string[] args)
            {
                // create/insert into BST
                BstNode Root = null;
                Root = Insert(Root, 15);
                Root = Insert(Root, 10);
                Root = Insert(Root, 20);
                Root = Insert(Root, 8);
                Root = Insert(Root, 12);
                Root = Insert(Root, 17);
                Root = Insert(Root, 25);
             }
    
    }
    

提交回复
热议问题