二叉搜索树及判断一棵树是否平衡

二叉搜索树的特点:
1. 每个节点都有一个作为搜索依据的关键码(key),所有节点的关键码互不相同。
2. 左子树上所有节点的关键码(key)都小于根节点的关键码(key)。
3. 右子树上所有节点的关键码(key)都大于根节点的关键码(key)。
4. 左右子树都是二叉搜索树。
一棵二叉搜索树如下图:
这里写图片描述

平衡二叉树的特点:
左右子树的高度差<=1
无法达到绝对平衡是因为:如果一棵二叉树只有两个节点,则高度差永远差1。

#pragma once
#include<iostream>
#include<stack>
using namespace std;

template <class K, class V>
struct BinarySearchTreeNode
{
    K _key;
    V _value;
    BinarySearchTreeNode<K, V>* _left;
    BinarySearchTreeNode<K, V>* _right;

    BinarySearchTreeNode(K& k, V& v)
        :_key(k)
        , _value(v)
        , _left(NULL)
        , _right(NULL)
    {}
};

template <class K, class V>
class BinarySearchTree
{
    typedef BinarySearchTreeNode<K, V> Node;
public:
    BinarySearchTree()
        : _root(NULL)
    {}
    bool Insert(K key, V val)
    {
        if (_root == NULL)
        {
            _root = new Node(key, val);
            return true;
        }
        Node *cur = _root;
        Node *prev = NULL; //保存cur的前一个节点
        while (cur)
        {
            if (key < cur->_key)
            {
                prev = cur;
                cur = cur->_left;
            }
            else if (key > cur->_key)
            {
                prev = cur;
                cur = cur->_right;
            }
            else //已经存在
                return false;
        }
        Node *node = new Node(key, val);
        if (key < prev->_key)
            prev->_left = node;
        else
            prev->_right = node;
        return true;
    }

    Node *Find(const K& key)
    {
        Node *cur = _root;
        while (cur)
        {
            if (key < cur->_key)
                cur = cur->_left;
            else if (key > cur->_key)
                cur = cur->_right;
            else //找到
                return cur;
        }
        return 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值