栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

剑指Offer15

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

剑指Offer15

34. 二叉树中和为某一值的路径




class Solution {
public:
    vector> res;
    vector tmp;
    vector> pathSum(TreeNode* root, int target) {
        if(!root){
            return res;
        }else
        {
            dfs(root, target);
        }
        return res;
    }
    void dfs(TreeNode* node, int target)
    {
        target -= node->val;
        tmp.push_back(node->val);
        if(node->left != nullptr){
            dfs(node->left, target);
        }
        if(node->right != nullptr){
            dfs(node->right, target);
        }
        if(node->left == nullptr && node->right == nullptr && target == 0){
            res.push_back(tmp);
        }
        tmp.pop_back();
    }
};
36. 二叉搜索树与双向链表





class Solution {
public:
    
    Node* treeToDoublyList(Node* root) {
        if(root == nullptr)
        {
            return nullptr;
        }
        inorder(root);
        head->left = pre;
        pre->right = head;
        return head;
    }
private:
    Node  *pre, *head;
    void inorder(Node* cur)
    {
        if(cur == nullptr){
            return;
        }
        inorder(cur->left);
        if(pre != nullptr)
        {
            pre->right = cur;
        }
        else 
        {
            head = cur;
        }
        cur->left = pre;
        pre = cur;
        inorder(cur->right);
    }
};
54. 二叉搜索树的第K大节点

class Solution {
public:
    int kthLargest(TreeNode* root, int k) {
        inorder(root, k);
        return res;
    }
    void inorder(TreeNode* root, int& k)
    {
        if(root == nullptr)
        {
            return;
        }
        inorder(root->right, k);
        if(k == 0){
            return;
        }
        if(--k == 0){
            res = root->val;
        }
        inorder(root->left, k);
    }
private:
    int res;
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/836667.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号