算法-树(重点中的重点)

一、树的递归

简单,这个地方我给整合一下模板。

void dfs(TreeNode *root){
	if(root == nullptr> return;
	// visit(root);		前序遍历
	dfs(root->left);
	// visit(root);		中序遍历
	dfs(root->right);
	// visit(root);		后续遍历
}

二、字典树模板

class TrieNode{
public:
    TrieNode* childNode[26];
    bool isVal;
    TrieNode(void):isVal(false){
        for(auto& node:childNode)   node = nullptr;
    }
};

class Trie{
    TrieNode* root;
public:
    Trie():root(new TrieNode()){}

    // 向字典树插入一个词
    void insert(string word){
        TrieNode* temp = root;
        for(int i = 0;i < word.size();++i){
            if(!temp->childNode[word[i] - 'a'])     temp->childNode[word[i] - 'a'] = new TrieNode();
            temp = temp->childNode[word[i] - 'a'];
        }
        temp->isVal = true;
    }

    // 判断字典树是否有一个词
    bool search(string word){
        TrieNode* temp = root;
        for(int i = 0;i < word.length();++i){
            if(!temp)       break;
            temp = temp->childNode[word[i] - 'a'];
        }
        return temp ? temp->isVal : false;
    }

    // 判断字典树是否有一个以词开始的前缀
    bool stratWith(string prefix){
        TrieNode* temp = root;
        for(int i = 0;i < prefix.size();++i){
            if(!temp)       break;
            temp = temp->childNode[prefix[i] - 'a'];
        }
        return temp != nullptr;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值