Binary Search Tree Learning Summary
BST Definition
BST is short for Binary Search Tree, by definition, the value of right node is always greater or equal to the root node, the value of left node is always less than the root node.
BST data structure and insert data
public class TreeNode<T>
{
public T data
{
get;
set;
} public TreeNode<T> leftChild
{
get;
set;
} public TreeNode<T> rightChild
{
get;
set;
}
}
public class BinarySearchTree<T> where T: IComparable
{
public TreeNode<T> root
{
get;
set;
} public BinarySearchTree()
{
root = null;
} public void Insert(T data)
{
TreeNode<T> temp = new TreeNode<T>();
temp.data = data;
TreeNode<T> current = root;
TreeNode<T> parent = null; if (root == null)
{
root = temp;
return;
} while (current != null)
{
parent = current;
if (current.data.CompareTo(data) > )
{
current = current.leftChild;
}
else
{
current = current.rightChild;
}
} // end of while if (data.CompareTo(parent.data) >= )
{
parent.rightChild = temp;
}
else
{
parent.leftChild = temp;
}
}
insert element to BST
1) if nothing is there, current element will be root node.
2) compare the value in BST, find the position of to be inserted, also track the parent reference. if found the position, compare the target value with parent node value, if less, insert to left, otherwise, insert to the right child.
Find Min from BST
Brutal force is to traverse the tree and also record the min value. However for BST, need to leverage its feature. becuase its value is kind of sorted.
so find min, continue find left until leaf node, which is the smallest value.
same pattern as above, if asked to find max, then starting from root node, find the right leaf node, then that one is the biggest value.
This is good optimization as you save some steps to traverse the whole tree.
Delete node with target value, which has two children
1. Find the target node firstly
2. if Found, check if in-order successor node is right child of to be deleted node, if is, replace the target node.
3. If the in-order successor node is not right child, replace the left node with root node.
4. Please make sure, current's parent left and child node reference needs be pointed to in-order successor node
5. Whenever you change the node, let it pointing to different node, please check the one pointing to it is updated firstly. we need ensure the sequence, otherwise, there might be loop reference.
public bool FindAndDeleteNodeIfItHasTwoChild(T key)
{
if (this.root == null)
{
return false;
} TreeNode<T> current = this.root;
TreeNode<T> parent = null;
TreeNode<T> nextSuccessorNode = null;
TreeNode<T> nextSuccessorParentNode = null; // locate the node
while (current != null)
{
if (key.CompareTo(current.data) == )
{
if (current.leftChild != null && current.rightChild != null)
{
FindInOrderNextSuccessor(current.rightChild, ref nextSuccessorNode, ref nextSuccessorParentNode); if (current.rightChild == nextSuccessorNode)
{
if (parent.leftChild == current)
{
parent.leftChild = nextSuccessorNode;
}
else if (parent.rightChild == current)
{
parent.rightChild = nextSuccessorNode;
} nextSuccessorNode.leftChild = current.leftChild; if (current == root)
{
this.root = nextSuccessorNode;
}
Console.WriteLine("NEXT SUCCESSOR node is right child of target node, replace");
}
else
{
// move up
nextSuccessorParentNode.leftChild = nextSuccessorNode.rightChild; nextSuccessorNode.leftChild = current.leftChild;
nextSuccessorNode.rightChild = current.rightChild;
if (parent != null)
{
if (parent.leftChild == current)
{
parent.leftChild = nextSuccessorNode;
}
else if (parent.rightChild == current)
{
parent.rightChild = nextSuccessorNode;
}
} if (current == root)
{
this.root = nextSuccessorNode;
}
} current.leftChild = null;
current.rightChild = null; return true;
}
else
{
Console.WriteLine("found the value, but it does not have two childs, return.");
return false;
}
} parent = current;
if (key.CompareTo(current.data) >= )
{
current = current.rightChild;
}
else
{
current = current.leftChild;
}
} return false;
}
Binary Search Tree Learning Summary的更多相关文章
- Binary search tree system and method
A binary search tree is provided for efficiently organizing values for a set of items, even when val ...
- [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法
二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...
- Leetcode 笔记 99 - Recover Binary Search Tree
题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...
- Leetcode 笔记 98 - Validate Binary Search Tree
题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...
- Leetcode: Convert sorted list to binary search tree (No. 109)
Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...
- [LeetCode] Closest Binary Search Tree Value II 最近的二分搜索树的值之二
Given a non-empty binary search tree and a target value, find k values in the BST that are closest t ...
- [LeetCode] Closest Binary Search Tree Value 最近的二分搜索树的值
Given a non-empty binary search tree and a target value, find the value in the BST that is closest t ...
- [LeetCode] Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列
Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary ...
- [LeetCode] Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最小共同父节点
Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BS ...
随机推荐
- saltstack 基本的批量操作
centos 6.5 saltstack 2015.5.10 (Lithium) 基本用法 # salt 'DEV-APP-001' cmd.run 'hostname' #指定被控端 # salt ...
- shell的交互式和非交互式登录
工作中经常碰见环境变量加载问题,归根结底就是配置文件的加载问题. 一般会有四种模式:交互式登陆.非交互式登陆.交互式非登陆.非交互非登陆. 交互式和非交互式对环境变量的加载: +----------- ...
- asp.net json,对象,字符串的相互转换
//object 转json格式字符串 public static string ObjectToJsonString(this object obj) { return JsonConvert.Se ...
- Bootstrap3基础 table-responsive 响应式表格
内容 参数 OS Windows 10 x64 browser Firefox 65.0.2 framework Bootstrap 3.3.7 editor ...
- luogu[愚人节题目3]现代妖怪殖民地 NTT
U34272 [愚人节题目3]现代妖怪殖民地 fft 题目链接 https://www.luogu.org/problemnew/show/U34272 思路 虽然是个py题. ntt(或者fft)模 ...
- Vue监听属性的变化
监听属性的变化watch: { counter: function (nval, oval) { alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!') }}
- Robot Framework问题记录
robotframework运行时后台报错UnicodeDecodeError UnicodeDecodeError :'utf-8' codec can't decode byte 0xb2 in ...
- java基础 (一)之HashMap
HashMap的存储结构是由数组和链表共同完成.Entry<K,V>[] ,Entry是单向链表. 1 HashMap数据结构 HashMap的底层主要是基于数组和链表来实现的,它之所以有 ...
- Verification of Model Transformations A Survey of the State-of-the-Art 模型转换的验证 对现状的调查
模型驱动工程范式认为软件开发生命周期由工件(需求规范.分析和设计文档.测试套件.源代码)支持,这些工件是表示要构建的系统不同视图的模型.存在一个由模型转换驱动的(半)自动构造过程,从系统的抽象模型开始 ...
- C语言获取Linux系统精确时间
gettimeofday()函数的使用方法 1.函数原型 #include <sys/time.h> int gettimeofday(struct timeval *tv, struct ...