Tree 树结构

news2024/9/27 9:26:59

Case 1st 最少的摄像头——亚马逊面试问题

给定一个二叉树,我们在树的节点上安装摄像头。

节点上的每个摄像机都可以监视其父级、自身及其直接子级。

计算监视树的所有节点所需的最小摄像机数。

alt

例:

Input: [0,0,null,0,0]
Output: 1
Explanation: One camera is enough to monitor all nodes if placed as shown.

了解问题:

由于我们希望尽量减少相机的数量,因此有一点很清楚,我们不会将相机放置在叶节点上。

所以我们可以从叶子到根追溯。这使得DFS成为解决问题的最可能选择。

但是当我们回溯时,我们需要在节点之间交换信息,以查看当前节点是否需要摄像头。

如果上一个节点已经有摄像头,我们不需要摄像头。总而言之,我们需要考虑以下事项:

如果当前节点是叶节点,则我们不需要相机。

如果我们在当前节点上没有摄像头,那么父节点需要它。

如果当前节点具有相机,则其父节点不需要相机。

我们可以分配不同的值来指示这些状态。-1 从孩子的意思是放相机。1 来自任何孩子意味着没有相机。

代码实现:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minCameraCover(self, root: TreeNode) -> int:
        def dfs(node):
            l=0
            r=0
            if (node.left is None and node.right is None):
                return -1
            if node.left:
                l = dfs(node.left)
            if node.right:
                r = dfs(node.right)
            if(l == -1 or r == -1):
                self.count += 1
                return 1
            if(l == 0 and r == 0):
                return -1
            if(l == 1 or r == 1):
                return 0
        self.count=0
        cams = dfs(root)
        if(cams == -1):
            self.count += 1
        return self.count

复杂性分析

时间复杂度:O(N),其中 N 是二叉树中的节点数

空间复杂性:递归调用堆栈的空间,可能是 N

Case 2nd 族谱

了解到家族成员的代际关系,我们想透过图的关系信息输入,返回任意某人是第几代?

英伟达和AMD之间是否存在完全竞争?下图显示了黄仁勋和苏丽莎家谱显示他们的关系有多密切?

alt

如何构造恰当的数据结构?

1、构造家庭成员的class类 FamilyMember

2、追加家庭成员的profile信息对应到树连接节点

3、如何输出打印

class类 FamilyMember

class FamilyMember:

    def __init__(self, name, gender, generation):
        self.name = name
        self.gender = gender
        self.generation = generation
        self.children = []
        self.parents = []


# 家族根
root = FamilyMember("John""Male", 0)

# John 的子女
child1 = FamilyMember("Jane""Female", 1)
child2 = FamilyMember("Mike""Male", 1)
root.children.append(child1)
root.children.append(child2)
child1.parents.append(root)
child2.parents.append(root)

#  Jane 和 Mike 的子女
grandchild1 = FamilyMember("Jay""Male", 2)
grandchild2 = FamilyMember("Joy""Female", 2)
...
child1.children.append(grandchild1)
child1.children.append(grandchild2)
grandchild1.parents.append(child1)
...

输出:

#递归
def print_family(member):
    print(f"{member.name} - {member.gender} - Generation {member.generation}")
    for child in member.children:
        print(" |--", end=""
        print_family(child)
        
print_family(root)

2.如何打印输出直观效果的家族树?

我们定义了一个print_family()函数,它能递归地打印指定家庭成员以及其子节点。

通过在每个节点前增加 "| "符号,就能形成一个漂亮的树形结构。 关键点是:

  1. 递归调用print_family(),打印每个子节点;

  2. 在子节点前增加 "|" 和"--"符号,形成一个缩进结构;

  3. 打印每个节点的时候,打印其名称、性别和代数信息;

执行print_family(root),就可以打印出整个家族结构。 可以看到,使用递归,就可以很简单地打印出一个复杂的树形结构。 你可能还想添加更多功能,比如:

  • 查找指定成员
  • 计算指定成员的后代数
  • 统计各代人口数
  • 画出家族结构图

这些都可以基于上述基本功能来实现。 通过分解为类、方法和函数,编码家族结构会更加模块化和可扩展。

John - Male - Generation 0
 |--Jane - Female - Generation 1
 |--Jay - Male - Generation 2
 |--Joy - Female - Generation 2
 |--Mike - Male - Generation 1

当我们想了解某个家族成员处于族谱中的第几代,如何构造算法?

def count_gen(Familytree, person):
    prev = set()
    for r in Familytree:
        while r not in prev:
            prev.add(r)
            r = tree[r]
    return len(skils)

致所有受到时间约束的工程师的任务清单

对于那些正在找工作的时间有限的工程师,这里有一份列出各类型问题中最好的LeetCode题目的列表,它可以教你每个类别/类型问题的核心概念和技巧!

许多其他LeetCode题目都是这些个别题目技巧的混合。 在我上一个求职过程中,我使用这个列表只做重要的题目。

如下:


•Arrays - Two Sum
•Strings - Longest Substring Without Repeating Characters
•Linked Lists - Reverse a Linked List
•Stacks - Validate Stack Sequences
•Queues - Implement Queue using Stacks
•Trees - Binary Tree Inorder Traversal
•Binary Search - Search Insert Position
•Sorting - Merge Sort
•Hash Tables - Two Sum
•Dynamic Programming - Climbing Stairs
•Greedy Algorithms - Maximum Units on a Truck
•Depth First Search - Number of Islands
•Breadth First Search - Clone Graph
•Bit Manipulation - Single Number
•Backtracking - Permutations
•Sliding Window - Maximum Sum Subarray of Size K
•Divide and Conquer - Merge Sorted Array
•Recursion - Reverse a String
•Binary Search Tree - Lowest Common Ancestor of a Binary Tree
•Heaps - Merge K Sorted Lists
•Trie - Implement Trie (Prefix Tree) (

Array

  • Two Sum - https://leetcode.com/problems/two-sum/
  • Best Time to Buy and Sell Stock - https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
  • Contains Duplicate - https://leetcode.com/problems/contains-duplicate/
  • Product of Array Except Self - https://leetcode.com/problems/product-of-array-except-self/
  • Maximum Subarray - https://leetcode.com/problems/maximum-subarray/
  • Maximum Product Subarray - https://leetcode.com/problems/maximum-product-subarray/
  • Find Minimum in Rotated Sorted Array - https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
  • Search in Rotated Sorted Array - https://leetcode.com/problems/search-in-rotated-sorted-array/
  • 3Sum - https://leetcode.com/problems/3sum/
  • Container With Most Water - https://leetcode.com/problems/container-with-most-water/

Binary

  • Sum of Two Integers - https://leetcode.com/problems/sum-of-two-integers/
  • Number of 1 Bits - https://leetcode.com/problems/number-of-1-bits/
  • Counting Bits - https://leetcode.com/problems/counting-bits/
  • Missing Number - https://leetcode.com/problems/missing-number/
  • Reverse Bits - https://leetcode.com/problems/reverse-bits/

Dynamic Programming

  • Climbing Stairs - https://leetcode.com/problems/climbing-stairs/
  • Coin Change - https://leetcode.com/problems/coin-change/
  • Longest Increasing Subsequence - https://leetcode.com/problems/longest-increasing-subsequence/
  • Longest Common Subsequence -
  • Word Break Problem - https://leetcode.com/problems/word-break/
  • Combination Sum - https://leetcode.com/problems/combination-sum-iv/
  • House Robber - https://leetcode.com/problems/house-robber/
  • House Robber II - https://leetcode.com/problems/house-robber-ii/
  • Decode Ways - https://leetcode.com/problems/decode-ways/
  • Unique Paths - https://leetcode.com/problems/unique-paths/
  • Jump Game - https://leetcode.com/problems/jump-game/

Graph

  • Clone Graph - https://leetcode.com/problems/clone-graph/
  • Course Schedule - https://leetcode.com/problems/course-schedule/
  • Pacific Atlantic Water Flow - https://leetcode.com/problems/pacific-atlantic-water-flow/
  • Number of Islands - https://leetcode.com/problems/number-of-islands/
  • Longest Consecutive Sequence - https://leetcode.com/problems/longest-consecutive-sequence/
  • Alien Dictionary (Leetcode Premium) - https://leetcode.com/problems/alien-dictionary/
  • Graph Valid Tree (Leetcode Premium) - https://leetcode.com/problems/graph-valid-tree/
  • Number of Connected Components in an Undirected Graph (Leetcode Premium) - https://leetcode.com/problems/number-of-connected-components-in-an-undirected-graph/

Interval

  • Insert Interval - https://leetcode.com/problems/insert-interval/
  • Merge Intervals - https://leetcode.com/problems/merge-intervals/
  • Non-overlapping Intervals - https://leetcode.com/problems/non-overlapping-intervals/
  • Meeting Rooms (Leetcode Premium) - https://leetcode.com/problems/meeting-rooms/
  • Meeting Rooms II (Leetcode Premium) - https://leetcode.com/problems/meeting-rooms-ii/

Linked List

  • Reverse a Linked List - https://leetcode.com/problems/reverse-linked-list/
  • Detect Cycle in a Linked List - https://leetcode.com/problems/linked-list-cycle/
  • Merge Two Sorted Lists - https://leetcode.com/problems/merge-two-sorted-lists/
  • Merge K Sorted Lists - https://leetcode.com/problems/merge-k-sorted-lists/
  • Remove Nth Node From End Of List - https://leetcode.com/problems/remove-nth-node-from-end-of-list/
  • Reorder List - https://leetcode.com/problems/reorder-list/

Matrix

  • Set Matrix Zeroes - https://leetcode.com/problems/set-matrix-zeroes/
  • Spiral Matrix - https://leetcode.com/problems/spiral-matrix/
  • Rotate Image - https://leetcode.com/problems/rotate-image/
  • Word Search - https://leetcode.com/problems/word-search/

String

  • Longest Substring Without Repeating Characters - https://leetcode.com/problems/longest-substring-without-repeating-characters/
  • Longest Repeating Character Replacement - https://leetcode.com/problems/longest-repeating-character-replacement/
  • Minimum Window Substring - https://leetcode.com/problems/minimum-window-substring/
  • Valid Anagram - https://leetcode.com/problems/valid-anagram/
  • Group Anagrams - https://leetcode.com/problems/group-anagrams/
  • Valid Parentheses - https://leetcode.com/problems/valid-parentheses/
  • Valid Palindrome - https://leetcode.com/problems/valid-palindrome/
  • Longest Palindromic Substring - https://leetcode.com/problems/longest-palindromic-substring/
  • Palindromic Substrings - https://leetcode.com/problems/palindromic-substrings/
  • Encode and Decode Strings (Leetcode Premium) - https://leetcode.com/problems/encode-and-decode-strings/

Tree

  • Maximum Depth of Binary Tree - https://leetcode.com/problems/maximum-depth-of-binary-tree/
  • Same Tree - https://leetcode.com/problems/same-tree/
  • Invert/Flip Binary Tree - https://leetcode.com/problems/invert-binary-tree/
  • Binary Tree Maximum Path Sum - https://leetcode.com/problems/binary-tree-maximum-path-sum/
  • Binary Tree Level Order Traversal - https://leetcode.com/problems/binary-tree-level-order-traversal/
  • Serialize and Deserialize Binary Tree - https://leetcode.com/problems/serialize-and-deserialize-binary-tree/
  • Subtree of Another Tree - https://leetcode.com/problems/subtree-of-another-tree/
  • Construct Binary Tree from Preorder and Inorder Traversal - https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/
  • Validate Binary Search Tree - https://leetcode.com/problems/validate-binary-search-tree/
  • Kth Smallest Element in a BST - https://leetcode.com/problems/kth-smallest-element-in-a-bst/
  • Lowest Common Ancestor of BST - https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
  • Implement Trie (Prefix Tree) - https://leetcode.com/problems/implement-trie-prefix-tree/
  • Add and Search Word - https://leetcode.com/problems/add-and-search-word-data-structure-design/
  • Word Search II - https://leetcode.com/problems/word-search-ii/

Heap

  • Merge K Sorted Lists - https://leetcode.com/problems/merge-k-sorted-lists/
  • Top K Frequent Elements - https://leetcode.com/problems/top-k-frequent-elements/
  • Find Median from Data Stream - https://leetcode.com/problems/find-median-from-data-stream/

二叉搜索树是如何实现的?(解决方案)

如何在给定的二叉树中执行预序遍历?(解决方案)

如何在没有递归的情况下以预序遍历给定的二叉树?(解决方案)

如何在给定的二叉树中执行无序遍历?(解决方案)

如何使用无序遍历打印给定二叉树的所有节点而不递归?(解决方案)

如何实现后序遍历算法?(解决方案)

如何在没有递归的情况下在后序遍历中遍历二叉树?(解决方案)

二叉搜索树的所有叶子是如何打印的?(解决方案)

你如何计算给定二叉树中的叶节点数?(解决方案)

如何在给定数组中执行二叉搜索?(解决方案)

如何在 Java 中将给定的二叉树转换为双链表?(解决方案)

​编写一个程序来查找 Java 中给定二叉树的深度?(解决方案)

二叉搜索树和二叉搜索树有什么区别?(答案)

什么是自平衡树?(答案)

什么是 AVL 树?(答案)

您给出了一个 BST,其中交换了两个节点?你如何恢复原始的BST?(解决方案)

如何在 Java 中将二叉树转换为二叉搜索树?(解决方案)

在 Java 中找到给定二叉树的最大 BST 子树?(解决方案)

编写一个 Java 程序来连接与二叉树相同级别的节点?(解决方案)

什么是 Trie 数据结构?(答案)

二叉树和Trie有什么区别?(答案)

如何检查给定的二叉树是否是BST?(解决方案)

如何计算给定二叉树中的叶节点数(解决方案)

如何在 Java 中打印给定二叉树的叶节点?(解决方案)

如何检查二叉树中是否存在给定节点?(解决方案)

如何在二叉搜索树中找到第 K 个最小元素?(解决方案)

如何在给定的二叉树中找到最大总和水平?(解决方案)

如何在爪哇中找到二叉树的最低共同祖先?(解决方案)

https://www.alivegarden.com/

本文由 mdnice 多平台发布

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/709639.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

asp.net宠物购物商城系统MyPetShop

asp.net宠物购物商城系统 在线购物网站,电子商务系统 主要技术: 基于asp.net架构和sql server数据库 功能模块: 用户可以购买宠物,查看订单记录 修改密码等 运行环境: 运行需vs2013或者以上版本,sql serv…

183 · 木材加工

链接:LintCode 炼码 - ChatGPT!更高效的学习体验! 题解:九章算法 - 帮助更多程序员找到好工作,硅谷顶尖IT企业工程师实时在线授课为你传授面试技巧 class Solution { public:/*** param l: Given n pieces of wood wi…

Java8 Stream详解

Stream类继承关系 前置知识 Spliterator接口使用 Spliterator是在java 8引入的一个接口,它通常和stream一起使用,用来遍历和分割序列。 只要用到stream的地方都需要Spliterator,比如List,Collection,IO channel等等…

大语言模型的百家齐放

基础语言模型 概念 基础语言模型是指只在大规模文本语料中进行了预训练的模型,未经过指令和下游任务微调、以及人类反馈等任何对齐优化。 如何理解 只包含纯粹的语言表示能力,没有指导性或特定目标。 只在大量无标注文本上进行无监督预训练,用于学习语言表示。 …

unity制作手游fps僵尸游戏

文章目录 介绍制作基本UI枚举控制角色移动切枪、设置音效、设置子弹威力、设置子弹时间间隔、换弹准星控制射击僵尸动画、血条设置导航 介绍 利用协程、枚举、动画器、导航等知识点。 实现移动、切枪、换弹、射击、僵尸追踪、攻击。 制作基本UI 制作人类血条、僵尸血条、移动按…

百度智能车竞赛丝绸之路1——智能车设计与编程实现控制

百度智能车竞赛丝绸之路1——智能车设计与编程实现控制 百度智能车竞赛丝绸之路2——手柄控制 一、项目简介 本项目现已基于鲸鱼机器人开发套件对其整体外形进行设计,并且对应于实习内容——以“丝绸之路”为题,对机器人各个功能与机器人结构部分进行相…

【几何数学】【Python】【C++】判断两条线段是否相交,若相交则求出交点坐标

判断线段是否相交的办法(使用了向量叉积的方法): 首先,通过给定的线段端点坐标p1、p2、p3和p4构建了四个向量v1、v2、v3和v4: v1表示从p1指向p2的向量,其分量为[p2[0] - p1[0], p2[1] - p1[1]]。 v2表示从…

Camtasia Studio2023标准版屏幕录制和视频剪辑软件

Camtasia Studio2023提供了强大的屏幕录像、视频的剪辑和编辑、视频菜单制作、视频剧场和视频播放功能等。它能在任何颜色模式下轻松地记录屏幕动作,包括影像、音效、鼠标移动的轨迹,解说声音等等,另外,它还具有及时播放和编辑压缩…

[前端]JS——join()与split()的使用

Array.join():数组转换为字符串,"()"里元素指定数组转为字符串用什么串联&#xff0c;默认为空。 Array.join()的使用&#xff1a; <script>let arr[1,2,3,4]console.log("arr未转换前:",arr,typeof(arr));console.log("arr使用join():"…

Netty核心技术八--Netty编解码器和handler的调用机制

1.基本说明 netty的组件设计&#xff1a;Netty的主要组件有Channel、EventLoop、ChannelFuture、 ChannelHandler、ChannelPipe等 ChannelHandler充当了处理入站和出站数据的应用程序逻辑的容器。 例如&#xff0c;实现ChannelInboundHandler接口&#xff08;或ChannelInbound…

Typora图床配置-OSS对象存储

Typora图床配置-OSS对象存储 1.PicGo下载 下载地址&#xff1a; Release 2.3.0 Molunerfinn/PicGo GitHub https://github.com/Molunerfinn/PicGo/releases/tag/v2.3.1 下载如下&#xff1a; 2.安装和配置 进入阿里云创建OSS对象存储服务。 设置为公共读才能被别人访问到。…

树与图的深度优先遍历

树的重心 本题的本质是树的dfs&#xff0c; 每次dfs可以确定以u为重心的最大连通块的节点数&#xff0c;并且更新一下ans。 也就是说&#xff0c;dfs并不直接返回答案&#xff0c;而是在每次更新中迭代一次答案。 这样的套路会经常用到&#xff0c;在 树的dfs 题目中 #includ…

IMU 互补滤波

IMU学名惯性测量单元&#xff0c;所有的运动都可以分解为一个直线运动和一个旋转运动&#xff0c;故这个惯性测量单元就是测量这两种运动&#xff0c;直线运动通过加速度计可以测量&#xff0c;旋转运动则通过陀螺。 void IMUupdate(float gx, float gy, float gz, float ax,fl…

Go 语言 context 都能做什么?

原文链接&#xff1a; Go 语言 context 都能做什么&#xff1f; 很多 Go 项目的源码&#xff0c;在读的过程中会发现一个很常见的参数 ctx&#xff0c;而且基本都是作为函数的第一个参数。 为什么要这么写呢&#xff1f;这个参数到底有什么用呢&#xff1f;带着这样的疑问&am…

postgresql数据库登录代理解析(包含登录协议包解析)

文章目录 postgresql数据库登录代理解析&#xff08;包含登录协议包解析&#xff09;背景描述版本不同对应的账号密码加密目标解析方法相关代码位置断点关键位置及相关重要变量 登录通信流程&#xff08;SCRAM-SHA-256方式&#xff09;代码实现相关参考资料 postgresql数据库登…

Python count()函数详解

「作者主页」&#xff1a;士别三日wyx 「作者简介」&#xff1a;CSDN top100、阿里云博客专家、华为云享专家、网络安全领域优质创作者 「推荐专栏」&#xff1a;对网络安全感兴趣的小伙伴可以关注专栏《网络安全入门到精通》 count 1、指定搜索位置2、参数为负数3、列表的coun…

以太网OSI参考模型(四)

目录 OSI模型 一、物理层 二、数据链路层 三、网络层 四、传输层 五、会话层 六、表示层 七、应用层 OSI模型 OSI七层模型&#xff0c;是国际标准化组织(ISO)和国际电报电话咨询委员会(CCITT)1984年联合制定的开放系统互联参考模型&#xff0c;为开放式互联信息系统提供…

06-C++学习笔记-指针的定义与使用

指针是C中非常重要的概念&#xff0c;它允许直接访问内存地址&#xff0c;并通过地址操作变量。本篇笔记将介绍指针的定义与使用方法&#xff0c;以及指针与数组的关系。 1️⃣ 指针的引入 指针的引入是为了解决需要直接访问内存地址的情况。通过指针&#xff0c;可以间接访问…

Android TextView 展示特殊字符高度变高问题解决

背景 #在我们的项目中&#xff0c;展示文字是很常见的需求&#xff0c;但是在线上展示中发现&#xff0c;有些信息是特殊字符展示的&#xff0c;而且这些字符的高度会导致TextView的高度变高&#xff08;与正常字符比&#xff09;。 效果如下&#xff1a; 很明显&#xff0…

森云+优控配置摄像头进行录像和拍照测试

森云和优控配置摄像头进行录像和拍照测试 现在其实已经基本上明确自己的环境了&#xff0c;就是在ubuntu下的pycharm和vscode&#xff0c;然后下载conda&#xff08;但是不要默认的base环境&#xff0c;只要conda create -n xxx 这样的基本功能就好了&#xff09; 显示opencv…