二叉树判断

Binary tree judgment

判断完全二叉树

思路

使用层序遍历的思想

  • 遇到节点左为空且右不为空,则不是

  • 遇到一个叶子节点,其后必全是叶子节点,否则不是

实现

bool isCBT(Node* root)
{
    if(root != null)
    {
        queue<Node*> Nodeque;
        Nodeque.push(root);
        bool leaf = false;
        while(!Nodeque.empty())
        {
            Node* Front = Nodeque.front();
            Nodeque.pop();
            
            /******遇到子节点后,后续必全是子节点******/
            if(leaf && (Front->left != null || Front->right != null))
            {
                return false;
            }
            /******左为空,又不为空,不是完全二叉树******/
            if(Front->left == null&&Front->right != null)
            {
                return false;
            }
            
            if(Front->left) Nodeque.push(Front->left);
            if(Front->right) Nodeque.push(Front->right);
            /******遇到第一个子节点******/
            if(!Front->left && !Front->right) leaf = true;
        }
    }
    return true;
}

判断搜索二叉树

数据

使用preValue表示左子树最后处理的数

思路

  • 使用中序遍历的思想

  • 比较preValueroot->value

实现

static int preValue = -1;
bool isSBT(Node* root)
{
    if(root == null) return true;
    
    bool isSBTleft = isSBT(root->left);
    if(!isSBTleft) return false;
    
    if(root->value <= preValue) return false;
    preValue = root->value;
    
    return isSBT(root->right);
}

总结

需要结合这两种二叉树的特性进行判断,考验对其结构的理解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值