找工作准备刷题day2 二叉树+贪心算法

第一题:二叉树的前、中、后序遍历

Leetcode 144.前序遍历:根、左、右
Leetcode 94.中序遍历:左、根、右
Leetcode 145.后序遍历:左、右、根
迭代遍历统一写法

// 以145 后序遍历为例
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> ans;
        if (root == nullptr)
            return ans;
        stack<TreeNode*> mystack;
        TreeNode* cur;
        mystack.push(root);
        while (!mystack.empty()) {
            cur = mystack.top();
            mystack.pop();
            if (cur != nullptr) {
                mystack.push(cur); // 根
                mystack.push(nullptr);

                if (cur->right)
                    mystack.push(cur->right); // 右
                if (cur->left)
                    mystack.push(cur->left); // 左
            } else {
                cur = mystack.top();
                mystack.pop();
                ans.push_back(cur->val);
            }
        }

        return ans;

    }
};

第二题:Leetcode102. 二叉树的层序遍历

题解

class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        vector<vector<int>> ans;
        queue<TreeNode*> que;
        TreeNode* node;
        if (root != nullptr)
            que.push(root);
        vector<int> level;
        size_t size;
        while (!que.empty()) {
            level.clear();
            size = que.size();
            for (int i = 0; i < size; i++) {
                node = que.front();
                que.pop();
                level.push_back(node->val);

                if (node->left != nullptr)
                    que.push(node->left);
                if (node->right != nullptr)
                    que.push(node->right);
            }

            ans.push_back(level);
        }

        return ans;
    }
};

要点

  1. queue,先进先出,接口有;front(),push(),pop(),empty()
  2. size需要每次循环前赋值,push后会改变

第三题:Leetcode455.分发饼干(贪心算法)

题解

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        sort(g.begin(), g.end());
        sort(s.begin(), s.end());
        int ans = 0;
        for (int i = 0; i < s.size(); i++) // 饼干
        {
            if (ans < g.size() && g[ans] <= s[i])
                ans++;
        }
        return ans;
    }
};

要点

  1. 贪心思路:每次拿出最小的饼干分给饭量最小的娃
  2. 时间复杂度:O(nlgn),空间复杂度:O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值