Zheaoli / do-something-right

MIT License
37 stars 3 forks source link

2022-06-22 #276

Open SaraadKun opened 2 years ago

SaraadKun commented 2 years ago

513. 找树左下角的值

class Solution {

    int maxDepth = 0;
    int ans;

    public int findBottomLeftValue(TreeNode root) {
        //dfs + 记录最大深度
        dfs(root, 1);
        return ans;
    }
    void dfs(TreeNode root, int depth) {
        if (root == null)
            return;
        if (depth > maxDepth) {
            maxDepth = depth;
            ans = root.val;
        }
        dfs(root.left, depth + 1);
        dfs(root.right, depth + 1);
    }
}

WeChat: Saraad

SaraadKun commented 2 years ago

215. Kth Largest Element in an Array

class Solution {
    public int findKthLargest(int[] nums, int k) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for(int i = 0; i< nums.length; i++) {
            if (i < k) {
                pq.offer(nums[i]);
            } else {
                if (nums[i] > pq.peek()) {
                    pq.poll();
                    pq.offer(nums[i]);
                }
            }
        }
        return pq.poll();
    }
}

WeChat: Saraad

dreamhunter2333 commented 2 years ago
#include <iostream>
#include <list>
using namespace std;
/*
 * @lc app=leetcode.cn id=513 lang=cpp
 *
 * [513] 找树左下角的值
 */
struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};
// @lc code=start
class Solution
{
public:
    int findBottomLeftValue(TreeNode *root)
    {
        list<TreeNode *> nodeList;
        nodeList.push_back(root);
        TreeNode *res;
        while (!nodeList.empty())
        {
            res = nodeList.front();
            int n = nodeList.size();
            for (int i = 0; i < n; i++)
            {
                TreeNode *node = nodeList.front();
                nodeList.pop_front();
                if (node->left != nullptr)
                {
                    nodeList.push_back(node->left);
                }
                if (node->right != nullptr)
                {
                    nodeList.push_back(node->right);
                }
            }
        }
        return res->val;
    }
};
// @lc code=end
int main()
{
    TreeNode node1 = TreeNode(1);
    TreeNode node3 = TreeNode(3);
    TreeNode node2 = TreeNode(2, &node1, &node3);
    cout << Solution().findBottomLeftValue(&node2) << endl;
    return 0;
}

微信id: 而我撑伞 来自 vscode 插件