public void BFS(Node root) { // breadth-first using a queue Queue<Node> queue = new Queue<Node>(); queue.Enqueue(root); while (queue.Count > 0) { var node = queue.Dequeue(); // display node node.displayNode(); if (node.Left != null) { queue.Enqueue(node.Left); } if (node.Right != null) { queue.Enqueue(node.Right); } } }
private void ReplaceNodeInParent(Node parent, Node self, Node newNode) { if (parent!=null) { if (parent.Left==self) { parent.Left = newNode; } else { parent.Right = newNode; } } else { // this is root _root = newNode; } }
//find min of sub tree and delete private int FindAndDeleteMin(Node parent, Node node) { Node current = node; Node _parent = parent; while (current.Left!=null) { _parent = current; current = current.Left; } int currentKey = current.item; // Delet current; if (current.Right!=null) { DeleteNodeWithRightChildOnly(_parent,current); } else { DeleteNodeWithWithNoChildren(_parent,current); } return currentKey; }
private void DeleteNodeWithWithNoChildren(Node parent, Node self) { if (parent==null) { // root _root = null; } else { if(parent.Left == self) { parent.Left = null; } else { parent.Right = null; } } }
private void DeleteNodeWithRightChildOnly(Node parent, Node self) { if (parent==null) { // root _root = self.Right; } else { if(parent.Left == self) { parent.Left = self.Right; } else { parent.Right = self.Right; } } }
public void Preorder(Node root) { // root, left, right if (root != null) { root.displayNode(); Preorder(root.Left); Preorder(root.Right); } }
public void PostOrder(Node root) { // left, right, root if (root != null) { PostOrder(root.Left); PostOrder(root.Right); root.displayNode(); } }
public BinarySearchTree2() { _root = null; }
public void Insert(int id) { Node newNode = new Node(); newNode.item = id; // Add new node if (_root == null) { // this is first node _root = newNode; } else { // do a search of newNode Node current = _root; Node parent = null; while (true) { parent = current; if (id < current.item) { // going down left current = current.Left; if (current == null) { parent.Left= newNode; return; } } else { // going down right current = current.Right; if (current == null) { parent.Right = newNode; return; } } } } }
public void InOrder(Node root) { // left, root, right, if (root != null) { InOrder(root.Left); root.displayNode(); InOrder(root.Right); } }
public void DFS(Node root) { // depth-first using a stack Stack<Node> stack = new Stack<Node>(); stack.Push(root); while (stack.Count > 0) { var node = stack.Pop(); // display node node.displayNode(); if (node.Left != null) { stack.Push(node.Left); } if (node.Right != null) { stack.Push(node.Right); } } }