Binary search tree
Contents
Binary search tree
Operations
Binary search trees should support 3 operations:
- insert element
- delete element
- find element
Find element
We have: tree Т and value K.
Problem: Check if exist node with value equal K – return this node.
Solution:
- If
Tis empty – return not found - Check
Kwith root nodeX.- If
K==X– return this node - If
K>Xrun recursion on right subtree of this node - If
K<Xrun recursion on left subtree of this node
- If
implementation:
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func searchBST(root *TreeNode, val int) *TreeNode {
if root == nil {
return nil
}
if root.Val == val {
return root
}
if root.Val > val {
return searchBST(root.Left, val)
}
return searchBST(root.Right, val)
}