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的更多相关文章

  1. Binary search tree system and method

    A binary search tree is provided for efficiently organizing values for a set of items, even when val ...

  2. [数据结构]——二叉树(Binary Tree)、二叉搜索树(Binary Search Tree)及其衍生算法

    二叉树(Binary Tree)是最简单的树形数据结构,然而却十分精妙.其衍生出各种算法,以致于占据了数据结构的半壁江山.STL中大名顶顶的关联容器--集合(set).映射(map)便是使用二叉树实现 ...

  3. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  4. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  5. Leetcode: Convert sorted list to binary search tree (No. 109)

    Sept. 22, 2015 学一道算法题, 经常回顾一下. 第二次重温, 决定增加一些图片, 帮助自己记忆. 在网上找他人的资料, 不如自己动手. 把从底向上树的算法搞通俗一些. 先做一个例子: 9 ...

  6. [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 ...

  7. [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 ...

  8. [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 ...

  9. [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 ...

随机推荐

  1. Mysql error 1317导致从库复制断开

    环境 :Percona Server for MySQL 5.5.18 1. 报错日志: 171212 19:59:58 [ERROR] Slave SQL: Query partially comp ...

  2. poj2115 C Looooops(exgcd)

    poj2115 C Looooops 题意: 对于C的for(i=A ; i!=B ;i +=C)循环语句,问在k位存储系统中循环几次才会结束. 若在有限次内结束,则输出循环次数. 否则输出死循环. ...

  3. Python3 pip命令报错:Fatal error in launcher: Unable to create process using '"'

    Python3 pip命令报错:Fatal error in launcher: Unable to create process using '"' 一.问题 环境:win7 同时安装py ...

  4. Python 静态方法,类方法,属性方法

    方法的使用 静态方法 - 只是名义上归类管理,实际上在静态方法里访问不了类或实例中的任何属性. class Dog(object): def __init__(self,name): self.nam ...

  5. shell-awk详细笔记

    shell # var="hexiaoqiang" # ${var//PATTERN/SUBSTI}:查找var所表示的字符串中,所有被PATTERN所匹配到的字符串,并将其全部替 ...

  6. 复旦大学2016--2017学年第一学期(16级)高等代数I期末考试第七大题解答

    七.(本题10分)  设 $A,B$ 均为 $m\times n$ 阶实矩阵, 满足 $A'B+B'A=0$. 证明: $$r(A+B)\geq\max\{r(A),r(B)\},$$并且等号成立的充 ...

  7. 论文笔记:Visual Question Answering as a Meta Learning Task

    Visual Question Answering as a Meta Learning Task ECCV 2018 2018-09-13 19:58:08 Paper: http://openac ...

  8. java jdk动态代理学习记录

    转载自: https://www.jianshu.com/p/3616c70cb37b JDK自带的动态代理主要是指,实现了InvocationHandler接口的类,会继承一个invoke方法,通过 ...

  9. hdu-5009 Paint Pearls DP+双向链表 with Map实现去重优化

    http://acm.hdu.edu.cn/showproblem.php?pid=5009 题目要求对空序列染成目标颜色序列,对一段序列染色的成本是不同颜色数的平方. 这题我们显然会首先想到用DP去 ...

  10. 『Python CoolBook』C扩展库_其一_用法讲解

    不依靠其他工具,直接使用Python的扩展API来编写一些简单的C扩展模块. 本篇参考PythonCookbook第15节和Python核心编程完成,值得注意的是,Python2.X和Python3. ...