什麼是二叉堆排序呢?node
就是上面這種,一個節點大於左節點,可是小於右節點,再我寫的例子中會寫出大於等於右節點。數組
那麼如何讓一個數組進行變成這種二叉樹呢?ide
其實只要有規律就很簡單。測試
第一個元素(0)做爲根節點。this
第二個元素若是比第一個元素則判斷是否有左節點,若是沒有左節點,就是它的左節點,若是有左節點就和它的左節點比較。code
直接上代碼吧:blog
public class BinarySortTree { //根節點 Node root; public BinarySortTree(Node root) { this.root = root; } public BinarySortTree() : this(null) { } public void add(Node node) { if (root == null) { root = node; } else { this.root.addNode(node); } } public void infixOrder() { if (root == null) { Console.WriteLine("root 爲空"); } else { root.infixOrder(); } } public Node searchNode(int value) { if (root==null) { Console.WriteLine("root 爲空"); } return root.searchNode(value); } } public class Node { public Node left; public Node right; int value; public int Value { get => value; set => this.value = value; } public Node(int value) { this.Value = value; } //中序排序 public void infixOrder() { if (this.left != null) { this.left.infixOrder(); } Console.WriteLine(this); if (this.right != null) { this.right.infixOrder(); } } public override string ToString() { return Value.ToString(); } //增長元素 public void addNode(Node node) { if (node.Value < this.Value) { if (this.left == null) { this.left = node; } else { this.left.addNode(node); } } else { if (this.right == null) { this.right = node; }else { this.right.addNode(node); } } } //查找元素 public Node searchNode(int value) { if (this.Value == value) { return this; } if (this.Value > value) { if (this.left != null) { return this.right.searchNode(value); } else { return null; } } else { if (this.left != null) { return this.left.searchNode(value); } else { return null; } } } }
測試代碼:排序
static void Main(string[] args) { int[] arr = { 7, 3, 10, 12, 5, 1, 9, 2 }; BinarySortTree binarySortTree = new BinarySortTree(); //循環的添加結點到二叉排序樹 for (int i = 0; i < arr.Length; i++) { binarySortTree.add(new Node(arr[i])); } //中序遍歷後的數據 binarySortTree.infixOrder(); Node node = binarySortTree.searchNode(7); Console.WriteLine("輸入7,查找結果爲:"+node.Value); //查找一個爲空元素 Node node100 = binarySortTree.searchNode(100); if (node100 == null) { Console.WriteLine("查找元素爲空"); } Console.Read(); }
測試結果:get
後面補一下刪除節點的,看下之前的丟了不。string