算法——树

二叉树遍历

二叉树的前序遍历

class Solution {
    vector<int> ans;

    // 递归
    void func1(TreeNode* root) {
        if (root == nullptr) {
            return ;
        }
        ans.push_back(root->val);
        func1(root->left);
        func1(root->right);
    }

    // 迭代
    void func2(TreeNode* root) {
        stack<TreeNode*> stk;
        TreeNode* ptr = root;
        while (!stk.empty() || ptr != nullptr) {
            while (ptr != nullptr) {
                ans.push_back(ptr->val);
                stk.push(ptr);
                ptr = ptr->left;
            }
            ptr = stk.top();
            stk.pop();
            ptr = ptr->right;
        }
    }
public:
    vector<int> preorderTraversal(TreeNode* root) {
        func1(root);
        return ans;
    }
};

二叉树的中序遍历

class Solution {
    vector<int> ans;

    // 递归
    void func1(TreeNode* root) {
        if (root == nullptr) {
            return ;
        }
        func1(root->left);
        ans.push_back(root->val);
        func1(root->right);
    }

    // 迭代
    void func2(TreeNode* root) {
        stack<TreeNode*> stk;
        TreeNode* ptr = root;
        while (!stk.empty() || ptr != nullptr) {
            while (ptr != nullptr) {
                stk.push(ptr);
                ptr = ptr->left;
            }
            ptr = stk.top();
            stk.pop();
            ans.push_back(ptr->val);
            ptr = ptr->right;
        }
    }
public:
    vector<int> inorderTraversal(TreeNode* root) {
        func1(root);
        return ans;
    }
};

二叉树的后序遍历

class Solution {
    vector<int> ans;

    // 递归
    void func1(TreeNode* root) {
        if (root == nullptr) {
            return ;
        }
        func1(root->left);
        func1(root->right);
        ans.push_back(root->val);
    }

    // 迭代
    void func2(TreeNode* root) {
        stack<TreeNode*> stk;
        TreeNode* ptr = root;
        TreeNode* prev = nullptr;
        while (!stk.empty() || ptr != nullptr) {
            // 遍历先将左节点入栈
            while (ptr != nullptr) {
                stk.push(ptr);
                ptr = ptr->left;
            }
            
            // 访问最左节点
            ptr = stk.top();
            stk.pop();

            // 判断是否有右子树,或者右子树是否访问过
            // 如果没有右子树,或者右子树已经访问完毕(当前节点的右节点是上一个被访问的节点)
            // 否则有右子树且没有被访问,那么访问右子树
            if (ptr->right == nullptr || ptr->right == prev) {
                // 此时左右子树应该均已访问完成
                ans.push_back(ptr->val);
                // 记录当前访问的节点,避免重复访问右子树
                prev = ptr;
                // 避免重复访问左子树
                ptr = nullptr;
            } else {
                stk.push(ptr);
                ptr = ptr->right;
            }
        }
    }
public:
    vector<int> postorderTraversal(TreeNode* root) {
        func2(root);
        return ans;
    }
};

Trie树

实现Trie树(前缀树)

class Trie {
    bool isEnd;// 字符串结尾标志
    Trie* next[26];
public:
    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }

    // 向前缀树中插入字符串 word
    void insert(string word) {
        Trie* cur = this;
        for (char c : word) {
            if (cur->next[c - 'a'] == nullptr) {
                cur->next[c - 'a'] = new Trie();
            }
            cur = cur->next[c - 'a'];
        }
        cur->isEnd = true;
    }

    // 查找字符串 word 是否存在
    bool search(string word) {
        Trie* cur = this;
        for (char c : word) {
            cur = cur->next[c - 'a'];
            if (cur == nullptr) {
                return false;
            }
        }
        return cur->isEnd;
    }

    // 查找已插入字符串是否有前缀 prefix
    bool startsWith(string prefix) {
        Trie* cur = this;
        for (char c : prefix) {
            cur = cur->next[c - 'a'];
            if (cur == nullptr) {
                return false;
            }
        }
        return true;
    }
};

添加与搜索单词

class Trie {
    bool isEnd;
    Trie* next[26];

public:
    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }

    void insert(string word) {
        Trie* cur = this;
        for (char c : word) {
            if (cur->next[c - 'a'] == nullptr) {
                cur->next[c - 'a'] = new Trie();
            }
            cur = cur->next[c - 'a'];
        }
        cur->isEnd = true;
    }

    bool search(string word, Trie* pre, int start) {
        if (pre == nullptr) {
            return false;
        }
        if (start == word.size()) {
            return pre->isEnd;
        }
        char c = word[start];
        if (c == '.') {
            for (Trie* nxt : pre->next) {
                if (search(word, nxt, start + 1)) {
                    return true;
                }
            }
        } else {
            return search(word, pre->next[c - 'a'], start + 1);
        }
        return false;
    }
};

class WordDictionary {
    Trie* tree;
public:
    WordDictionary() {
        tree = new Trie();
    }
    
    void addWord(string word) {
        tree->insert(word);
    }
    
    bool search(string word) {
        return tree->search(word, tree, 0);
    }
};

单词搜索II

class Trie {
public:
    bool isEnd;
    Trie* next[26];

    Trie() {
        isEnd = false;
        memset(next, 0, sizeof(next));
    }

    void insert(string word) {
        Trie* cur = this;
        for (char c : word) {
            if (cur->next[c - 'a'] == nullptr) {
                cur->next[c - 'a'] = new Trie();
            }
            cur = cur->next[c - 'a'];
        }
        cur->isEnd = true;
    }

    bool search(string word) {
        Trie* cur = this;
        for (char c : word) {
            cur = cur->next[c - 'a'];
            if (cur == nullptr) {
                return false;
            }
        }
        return cur->isEnd;
    }
};

class Solution {
    Trie* trie = new Trie();
    unordered_set<string> st;

    int dx[4] = {0, 1, 0, -1};
    int dy[4] = {1, 0, -1, 0};

    void dfs(vector<vector<char>>& board, int x, int y, string s, Trie* cur) {
        if (s.size() > 10 || cur == nullptr) return ;

        int m = board.size(), n = board[0].size();
        if (cur->isEnd) {
            st.insert(s);
        }

        for (int i = 0; i < 4; i ++) {
            int nx = x + dx[i], ny = y + dy[i];
            if (nx >= 0 && nx < m && ny >= 0 && ny < n && board[nx][ny] != '#') {
                char ch = board[nx][ny];
                board[nx][ny] = '#';
                dfs(board, nx, ny, s + ch, cur->next[ch - 'a']);
                board[nx][ny] = ch;
            }
        }
    }
public:
    vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
        int m = board.size(), n = board[0].size();
        
        for (string w : words) {
            trie->insert(w);
        }
        
        string s = "";
        for (int i = 0; i < m; i ++) {
            for (int j = 0; j < n; j ++) {
                char ch = board[i][j];
                board[i][j] = '#';
                dfs(board, i, j, s + ch, trie->next[ch - 'a']);
                board[i][j] = ch;
            }
        }

        vector<string> ans;
        for (auto& word : st) {
            ans.push_back(word);
        }
        return ans;
    }
};

其他

对称二叉树

class Solution {
    bool recur(TreeNode* l, TreeNode* r) {
        if (l == nullptr && r == nullptr) return true;
        if (l == nullptr || r == nullptr || l->val != r->val) return false;
        return recur(l->left, r->right) && recur(l->right, r->left);
    }
public:
    bool isSymmetric(TreeNode* root) {
        if (!root) return true;
        return recur(root->left, root->right);
    }
};

从前序与中序遍历序列构造二叉树

  • 前序遍历:根 - 左 - 右;中序遍历:左 - 根 - 右
class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        unordered_map<int, int> idx;
        for (int i = 0; i < n; i ++) {
            idx[inorder[i]] = i;
        }

        // 左闭右开区间
        function<TreeNode*(int, int, int, int)> dfs =
            [&](int preL, int preR, int inL, int inR) -> TreeNode* {
            if (preL == preR) { // 子树为空
                return nullptr;
            }
            int leftSize = idx[preorder[preL]] - inL; // 左子树的大小

            // 递归左子树的区间范围建立左子树
            TreeNode* left =
                dfs(preL + 1, preL + 1 + leftSize, inL, inL + leftSize);
            // 递归右子树的区间范围建立右子树
            TreeNode* right =
                dfs(preL + 1 + leftSize, preR, inL + 1 + leftSize, inR);
            return new TreeNode(preorder[preL], left, right);
        };

        return dfs(0, n, 0, n);
    }
};

从中序与后序遍历序列构造二叉树

  • 后序遍历:左 - 右 - 根;中序遍历:左 - 根 - 右
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
    int n = inorder.size();
    unordered_map<int, int> idx;
    for (int i = 0; i < n; i ++) {
        idx[inorder[i]] = i;
    }

    function<TreeNode*(int, int, int, int)> dfs =
    [&](int inL, int inR, int postL, int postR) -> TreeNode* {
        if (inL > inR) {
            return nullptr;
        }
        int leftSize = idx[postorder[postR]] - inL;

        TreeNode* left =
        dfs(inL, inL + leftSize - 1, postL, postL + leftSize - 1);
        TreeNode* right =
        dfs(inL + leftSize + 1, inR, postL + leftSize, postR - 1);
        return new TreeNode(postorder[postR], left, right);
    };

    return dfs(0, n - 1, 0, n - 1);
}
};

有序链表转换二叉搜索树

class Solution {
    ListNode* head;

    TreeNode* recur(int l, int r) {
        if (l > r) {
            return nullptr;
        }

        int mid = l + r >> 1;
        TreeNode* left = recur(l, mid - 1);
        TreeNode* node = new TreeNode(head->val);
        head = head->next;
        node->left = left;
        node->right = recur(mid + 1, r);
        return node;
    }
public:
    TreeNode* sortedListToBST(ListNode* head) {
        this->head = head;
        int len = 0;
        ListNode* p = head;
        while (p != nullptr) {
            len ++;
            p = p->next;
        }
        return recur(0, len - 1);
    }
};

路径总和II

class Solution {
    vector<vector<int>> ans;
    vector<int> path;

    void dfs(TreeNode* root, int tar) {
        if (root == nullptr) {
            return ;
        }
        
        path.push_back(root->val);
        tar -= root->val;
        if (root->left == root->right && tar == 0) {
            ans.push_back(path);
        }
        dfs(root->left, tar);
        dfs(root->right, tar);
        path.pop_back();
    }

public:
    vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
        dfs(root, targetSum);
        return ans;
    }
};

填充每个节点的下一个右侧节点指针II

class Solution {
public:
    Node* connect(Node* root) {
        Node* dummy = new Node();
        Node* cur = root;
        while (cur != NULL) {
            dummy->next = NULL;
            Node* nxt = dummy;
            while (cur != NULL) {
                if (cur->left != NULL) {
                    nxt->next = cur->left;
                    nxt = nxt->next;
                }
                if (cur->right != NULL) {
                    nxt->next = cur->right;
                    nxt = nxt->next;
                }
                cur = cur->next;
            }
            cur = dummy->next;
        }
        delete dummy;
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值