1135 Is It A Red-Black Tree 测试点2和3

我先吐为敬!

(5) For each node, all simple paths from the node to descendant leaves contain the same number of black nodes.
这个性质一定要搜索到NULL 节点再来判断。否则就有可能出现你认为是红黑树,但它不是红黑树
如:
在这里插入图片描述
我比较老实按照算法笔记来建造树:
思路就是

  • 因为是二叉搜索树,所以可以直接知道中序遍历,根据中序和前序遍历来构建树;
  • 构建好树之后DFS一直搜索到NULL节点,然后判断黑色的数量。这里直接判断根节点到NULL节点的黑色数量就好了,不需要每个节点单独去判断。一样的。
  • 还要注意就是根节点必须是黑色
#include<vector>
#include<cstdio>
#include<algorithm>
#include<unordered_map>
using namespace std;
struct Node{
   
   
    int val;
    Node*left;Node*right;
    Node(int v){
   
   
        val=v;
        right=left=NULL;
    }
};
vector<int>preorder;vector<int>inorder;
unordered_map<int,int> hashmap;
Node*create(int prel,int prer,int inl,int inr){
   
   
    if(prel>prer) return NULL;
    int k;
    for(k=inl;k<=inr;k++){
   
   
        if(preorder[prel]==inorder[k]) break;
    }
    int num=k-inl;
    Node*root=new Node
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值