力扣第二十五天(Tree topic)

本文探讨了在给定二叉树中找到两个节点的低阶共同祖先问题,提供了两种解决方案:深度优先搜索和使用父指针,同时介绍了如何序列化和反序列化二叉树以进行数据存储与重构。第一种方法虽简单但时间复杂度较高,第二种通过减少搜索空间提高了效率。还讨论了两个常见问题的解决方案,一个是序列化二叉树兼顾前序和中序遍历,另一个是快速的二叉树序列化与反序列化避免了TLE问题。
摘要由CSDN通过智能技术生成

problem Ⅰ

236. Lowest Common Ancestor of a Binary Tree
Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).”

Example 1:
在这里插入图片描述

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1
Output: 3
Explanation: The LCA of nodes 5 and 1 is 3.

Example 2:

在这里插入图片描述

Input: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4
Output: 5
Explanation: The LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [1,2], p = 1, q = 2
Output: 1

my solution 1 DFS

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* ans;
    int rec(TreeNode* root, TreeNode* p, TreeNode* q){
        if(!root)return 0;
        int left = rec(root->left, p, q);
        int right = rec(root->right, p, q);
        int mid = (root == p || root == q);
        if(mid + left + right >=2)
            ans = root;
        return (mid + left + right > 0);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        rec(root, p, q);
        return ans;
    }
};

time complexity : O ( n ) O(n) O(n)
space complexity : O ( n ) O(n) O(n)

my solution 2 use parent pointer

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        unordered_map<TreeNode*, TreeNode*> maps;
        stack<TreeNode*> stk;
        stk.push(root);
        maps.insert({root, NULL});
        while(maps.find(p)==maps.end() || maps.find(q)==maps.end()){
            TreeNode* top = stk.top();
            stk.pop();
            if(top->right){
                stk.push(top->right);
                maps.insert({top->right, top});
            }
            if(top->left){
                stk.push(top->left);
                maps.insert({top->left, top});
            }
        }
        unordered_set<TreeNode*> sets;
        while(p){
            sets.insert(p);
            p = maps[p];
        }
        while(q){
            if(sets.find(q) != sets.end())
                return q;
            q = maps[q];
        }
        return NULL;
    }
};

在这里插入图片描述
time complexity : O ( n ) O(n) O(n)
space complexity : O ( n ) O(n) O(n)
this solution reduce the search space, but because it is a Heuristic problem,so it is hard to calculate the complexity

problem Ⅱ

297. Serialize and Deserialize Binary Tree
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.

Design an algorithm to serialize and deserialize a binary tree. There is no restriction on how your serialization/deserialization algorithm should work. You just need to ensure that a binary tree can be serialized to a string and this string can be deserialized to the original tree structure.

Clarification: The input/output format is the same as how LeetCode serializes a binary tree. You do not necessarily need to follow this format, so please be creative and come up with different approaches yourself.

Example 1:

在这里插入图片描述

Input: root = [1,2,3,null,null,4,5]
Output: [1,2,3,null,null,4,5]

Example 2:

Input: root = []
Output: []

solution 1 TLE

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:

    // Encodes a tree to a single string.
    string serialize(TreeNode* root) {
        string res = "";
        stack<TreeNode*> stk;
        TreeNode* tmp = root;
        stk.push(root);
        while(!stk.empty()){
            TreeNode* top = stk.top();
            res.push_back(top->val);
            while(top->left){
                stk.push(top->left);
                top = top->left;
            }
            if(top->right)
                stk.push(top->right);
        }
        
        stk.push(root);
        while(!stk.empty()){
            TreeNode* top = stk.top();
            while(top->left){
                stk.push(top->left);
                top = top->left;
            }
            res.push_back(top->val);
            if(top->right)
                stk.push(top->right);
        }
        return res;
    }

    // Decodes your encoded data to tree.
    int preorderIndex = 0;
    TreeNode* rec(string preorder, string inorder, int low, int high){
        if(low > high)return NULL;
        TreeNode *root = new TreeNode(preorder[preorderIndex++]);
        int InorderPos;
        for(int i=low; i<=high; i++){
            if(inorder[i] == root->val){
                InorderPos = i;
                break;
            }
        }
        root->left = rec(preorder, inorder, low, InorderPos-1);
        root->right = rec(preorder, inorder, InorderPos+1, high);
        return root;
    }
    TreeNode* deserialize(string data) {
        int len = data.size();
        string preorder = data.substr(0, len/2);
        string inorder = data.substr(len, len/2);
        return rec(preorder, inorder, 0, preorder.size()-1);
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));

NOTE :
i want to get a string contain both the preorder traversals and inorder traversals, and then deserilize it
but finally i got a TLE…

solution 2

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Codec {
public:
     string serialize(TreeNode* root) {
        if(!root) {
         return "NULL,";
        }
        return to_string(root->val)+","+serialize(root->left)+serialize(root->right);
    }

    // Decodes your encoded data to tree.
    TreeNode* deserialize(string data) {
        queue<string> q;
        string s;
        for(int i=0;i<data.size();i++)
        {
            if(data[i]==',')
            {
                q.push(s);
                s="";
                continue;
            }
            s+=data[i];
        }
        if(s.size()!=0)q.push(s);
        return deserialize_helper(q);
    }

    TreeNode* deserialize_helper(queue<string> &q) {
        string s=q.front();
        q.pop();
        if(s=="NULL")return NULL;
        TreeNode* root=new TreeNode(stoi(s));
        root->left=deserialize_helper(q);
        root->right=deserialize_helper(q);
        return root;
    }
};

// Your Codec object will be instantiated and called as such:
// Codec ser, deser;
// TreeNode* ans = deser.deserialize(ser.serialize(root));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
力扣题礼盒的最大密度问题可以转化为一个函数 f(x) 的形式,其中 f(x) 表示 "礼盒中最大数不超过 x" 这个条件下的密度。 具体地,对于一个给定的数 x,我们可以使用贪心算法来判断在不超过 x 的情况下,最多能拿到多少的礼盒。假设当前已经拿到了 k 个礼盒,其数分别为 d1, d2, ..., dk,且满足 d1 <= d2 <= ... <= dk。此时,我们可以从剩余的礼盒中选择一个最小的数大于 dk 的礼盒,加入到已拿到的礼盒中,直到不能再加入礼盒为止。这个贪心算法的时间复杂度是 O(nlogn),其中 n 是礼盒的数量。 对于一个给定的数 x,如果能拿到的最多数不超过 x,则 f(x) 为 true,否则 f(x) 为 false。这个函数的曲线是一个阶梯状的函数,如下图所示: ``` | | | | | | | | | | |___|___|___|___ x1 x2 x3 x4 ``` 其中,每个竖直的线段表示一个礼盒,x1、x2、x3、x4 分别表示四个礼盒的最大数,每个水平的线段表示函数值为 true 的区间。例如,当 x 取值在 [x3, x4] 区间内时,f(x) 的值都为 true,因为在不超过 x3 的情况下,最多能拿到的数为 3+4+4=11,不超过 x4 的限制。 我们要找到的最大的密度,就是最后一个函数值为 true 的点所对应的 x 值,即 x4。这个问题可以通过二分查找法解决,每次取中间值,判断中间值是否满足条件,然后不断缩小搜索区间,最终找到最大的 x 值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值