Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public List<int> Bfs()
- {
- var list = new List<int>();
- Bfs(this.Root, list);
- return list;
- }
- private void Bfs(BinaryTreeNode root, List<int> list)
- {
- if (root == null)
- {
- return;
- }
- Queue<BinaryTreeNode> queue = new Queue<BinaryTreeNode>();
- queue.Enqueue(root);
- while (queue.Count > 0)
- {
- var node = queue.Dequeue();
- list.Add(node.Value);
- if (node.LeftChild != null)
- queue.Enqueue(node.LeftChild);
- if (node.RightChild != null)
- queue.Enqueue(node.RightChild);
- }
- }
- public int Height()
- {
- return Height(this.Root);
- }
- private int Height (BinaryTreeNode node)
- {
- if (node == null)
- {
- return -1;
- }
- return (1 + Math.Max(Height(node.LeftChild), Height(node.RightChild)));
- }
- public BinaryTreeNode Remove(int value)
- {
- BinaryTreeNode current = this.Root;
- BinaryTreeNode parent = this.Root;
- bool isLeftChild = false;
- if (current == null)
- {
- return null;
- }
- while( current.Value != value)
- {
- parent = current;
- if (current == null)
- {
- return null;
- }
- if (value < current.Value)
- {
- current = current.LeftChild;
- isLeftChild = true;
- }
- else
- {
- current = current.RightChild;
- isLeftChild = false;
- }
- }
- if (current.LeftChild == null && current.RightChild ==null)
- {
- if (current == this.Root)
- {
- this.Root = null;
- }
- else
- {
- if (isLeftChild)
- {
- parent.LeftChild = null;
- }
- else
- {
- parent.RightChild = null;
- }
- }
- }
- else if (current.RightChild==null)
- {
- if (current==this.Root)
- {
- this.Root = current.LeftChild;
- }
- else
- {
- if (isLeftChild)
- {
- parent.LeftChild = current.LeftChild;
- }
- else
- {
- parent.RightChild = current.LeftChild;
- }
- }
- }
- else if (current.LeftChild==null)
- {
- if(current == this.Root)
- {
- this.Root = current.RightChild;
- }
- else
- {
- if (isLeftChild)
- {
- parent.LeftChild = current.RightChild;
- }
- else
- {
- parent.RightChild = current.RightChild;
- }
- }
- }
- else
- {
- BinaryTreeNode successor = GetSuccessor(current);
- if (current == this.Root)
- {
- this.Root = successor;
- }
- else if (isLeftChild)
- {
- parent.LeftChild = successor;
- }
- else
- {
- parent.RightChild = successor;
- }
- }
- return this.Root;
- }
- private BinaryTreeNode GetSuccessor(BinaryTreeNode node)
- {
- BinaryTreeNode successorParent = node;
- BinaryTreeNode successor= node;
- BinaryTreeNode current = node.RightChild;
- while (current!=null)
- {
- successorParent = successor;
- successor = current;
- current = current.LeftChild;
- }
- if (successor!= node.RightChild)
- {
- successorParent.LeftChild = successor.RightChild;
- successor.RightChild = node.RightChild;
- }
- successor.LeftChild = node.LeftChild;
- return successor;
- }
Advertisement
Add Comment
Please, Sign In to add comment