Proof-of-stake

tags: Blockchain,Blockchain Proof,Ethereum,Solana source: https://ethereum.org/en/developers/docs/consensus-mechanisms/pos/ Proof workflow: Users stake money(ETH) to become a validator. Validators are chosen at random to create blocks and are responsible for checking and confirming blocks they don’t create. user’s stake is also used as a way to incentivise good validator behavior. For example, a user can lose a portion of their stake for things like going offline (failing to validate) or their entire stake for deliberate collusion. ...

January 4, 2022 · 1 min · Gray King

Proof-of-work

tags: Blockchain Proof,Blockchain,Ethereum source: https://ethereum.org/en/developers/docs/consensus-mechanisms/pow/ Wikipedia: https://en.wikipedia.org/wiki/Proof%5Fof%5Fwork A key feature of proof-of-work schemes is their asymmetry: the work – the computation – must be moderately hard (yet feasible) on the prover or requester side but easy to check for the verifier or service provider. With a hash function, let’s say SHA-1. For example, to do PoW, we need to generate a SHA-1 hash of the given data that must begins 52 binary zeros, that is 13 hexadecimal zeros: ...

January 4, 2022 · 1 min · Gray King

Blockchain Proof

tags: Blockchain

January 4, 2022 · 1 min · Gray King

Shinobi Systems' Solana Proof of Stake + Proof of History Primer

tags: Blockchain,Solana,Proof-of-stake,Proof-of-history source: “Shinobi Systems’ Solana Proof of Stake + Proof of History Primer.” Accessed January 5, 2022. https://www.shinobi-systems.com/primer.html.

January 4, 2022 · 1 min · Gray King

Blockchain Demo

tags: Video: Blockchain 101 - A Visual Demo,区块链, Online Tools source: https://andersbrownworth.com/blockchain/hash

January 3, 2022 · 1 min · Gray King

Video: Blockchain 101 - A Visual Demo

tags: 区块链 source: https://youtu.be/%5F160oMzblY8 It’s like Git but not support merge. The progress of changing blocks like git rebase.

January 3, 2022 · 1 min · Gray King

C/C++ 多态

tags: C/C++ 只能通过抽象类的指针或引用调用动态解析子类函数,虚函数表示需要动态解析,纯虚函数必须被子类覆盖,否则无法实例化。

January 2, 2022 · 1 min · Gray King

JavaScript

tags: Programming Language

January 2, 2022 · 1 min · Gray King

Swift

tags: Programming Language

January 2, 2022 · 1 min · Gray King

《深入理解计算机系统》读书笔记

tags: Computer Systems,读书笔记

January 2, 2022 · 1 min · Gray King

SO: What is the difference between iter and into_iter?

tags: Rust source: https://stackoverflow.com/a/34745885/2873718

January 1, 2022 · 1 min · Gray King

GitHub: Rust Memory Container Cheat-sheet

tags: Rust Wrapper Types,Rust source: Rust Memory Container Cheat-sheet

January 1, 2022 · 1 min · Gray King

Wrapper Types in Rust: Choosing Your Guarantees

tags: Rust,Rust Wrapper Types source: https://manishearth.github.io/blog/2015/05/27/wrapper-types-in-rust-choosing-your-guarantees/

January 1, 2022 · 1 min · Gray King

GitHub: Internal details of Tokio from code to designs

tags: Tokio source: https://github.com/tony612/tokio-internals

January 1, 2022 · 1 min · Gray King

PAPER: Raft

tags: Raft source: https://web.stanford.edu/~ouster/cgi-bin/papers/OngaroPhD.pdf

January 1, 2022 · 1 min · Gray King

PAPER: Time, Clocks, and the Ordering of Events in a Distributed System

tags: 分布式,一致性 source: https://lamport.azurewebsites.net/pubs/time-clocks.pdf The Big Problem The event order in a distributed system. The defination of a distributed system: the order of its events occurred is unpredictable, sometimes it’s impossiable to say a event occurred before another. How this paper try to solve this problem: use a “happened before” relation to define a partial ordering and distributed algorithm. Background

January 1, 2022 · 1 min · Gray King

CSDN: 理解这两点,也就理解了paxos协议的精髓

tags: Paxos source: https://blog.csdn.net/qq%5F35440678/article/details/78080431

January 1, 2022 · 1 min · Gray King

GitHub: raft-rs

tags: Rust,Raft source: https://github.com/tikv/raft-rs

January 1, 2022 · 1 min · Gray King

Raft Understandable Distributed Consensus

tags: Raft,分布式,分布式共识,Online Tools source: http://thesecretlivesofdata.com/raft/

January 1, 2022 · 1 min · Gray King

Distributed consensus (blockchain) simulation and visualization

tags: 分布式共识,Online Tools,区块链 source: https://web3scout.github.io/forcecons-sim/

January 1, 2022 · 1 min · Gray King

Org-roam export backlinks on Hugo

tags: org-roam, Org Mode source: https://seds.nl/notes/org%5Froam%5Fexport%5Fbacklinks%5Fon%5Fhugo/ https://seds.nl/notes/export%5Forg%5Froam%5Fbacklinks%5Fwith%5Fgohugo/ 利用 hugo 的 partial template layouts/partials/backlinks.html {{ $re := $.File.BaseFileName }} {{ $backlinks := slice }} {{ range .Site.AllPages }} {{ if and (findRE $re .RawContent) (not (eq $re .File.BaseFileName)) }} {{ $backlinks = $backlinks | append . }} {{ end }} {{ end }} <hr> {{ if gt (len $backlinks) 0 }} <div class="bl-section"> <h4>Links to this note</h4> <div class="backlinks"> <ul> {{ range $backlinks }} <li><a href="{{ .RelPermalink }}">{{ .Title }}</a></li> {{ end }} </ul> </div> </div> {{ else }} <div class="bl-section"> <h4>No notes link to this note</h4> </div> {{ end }} 然后插入到的 single.html 就行 ...

December 31, 2021 · 1 min · Gray King

Online Tools

tags: Tools

December 31, 2021 · 1 min · Gray King

RoamResearch

tags: Taking Notes,Online Tools

December 31, 2021 · 1 min · Gray King

Roam: Why I Love It and How I Use It

tags: Learning,Taking Notes source: https://www.nateliason.com/blog/roam

December 31, 2021 · 1 min · Gray King

How To Take Smart Notes: 10 Principles to Revolutionize Your Note-Taking and Writing

tags: Learning,Taking Notes,RoamResearch source: https://fortelabs.co/blog/how-to-take-smart-notes/ Luhmann’s slip-box: build second brain context – its network of associations, relationships, and connections to other information. But Luhmann often remarked that he never forced himself to do anything he didn’t feel like doing: “I only do what is easy. I only write when I immediately know how to do it. If I falter for a moment, I put the matter aside and do something else” (Luhmann et al., 1987, 154f). ...

December 31, 2021 · 2 min · Gray King

How To Take Smart Notes With Org-mode

tags: Learning,Taking Notes,org-roam,Org Mode source: https://blog.jethro.dev/posts/how%5Fto%5Ftake%5Fsmart%5Fnotes%5Forg/ Notes aren’t a record of my thinking process. They are my thinking process. – Richard Feynman The primary purpose of note-taking should not be for storing ideas, but for developing them. When we take notes, we should ask: “In what context do I want to see this note again?” Note-taking for writing: Find topic/research question Research/find literature Read and take notes Draw conclusions / outline text Write Two types of notes: ...

December 31, 2021 · 1 min · Gray King

Learning

December 31, 2021 · 0 min · Gray King

读书笔记

December 10, 2021 · 0 min · Gray King

加解密

证书 [译] 写给工程师:关于证书(certificate)和公钥基础设施(PKI)的一切(SmallStep, 2018)

October 9, 2021 · 1 min · Gray King

英语读音规则

tags: Learning English 一般现在时第三人称单音形规则 一般过去时音形规则

September 25, 2021 · 1 min · Gray King

英语词法

tags: Learning English 比较级 形容词/副词比较级 常规单音节词 -er fast -> faster small -> smaller nice -> nicer large -> larger(删除词尾不发音的 e) -y -> -ier busy -> busier pretty -> prettier 短元音 + 辅音:重写辅音 -er big -> bigger hot -> hotter 多音节: more + diffcult -> more difficult interesting -> more interesting careful /kɛəful/ -> more careful -y 二音节词(-ly副词除外):常不加 more busy -> busier pretty -> prettier quickly -> more quickly 特殊 much/many -> more little -> less good/well -> better bad -> worse 代词比较级 more less 比较级修饰 a little/ a bit + 比较级 更…一点 much / a lot / far + 比较级 更…得多 英语常见词用法 open/close 静态和动态 open When do you open(v.)? 强调动态,时间点 We are open at 9 every day. When are you open(adj.)? 强调静态,时间段 We are open from 9 to 6 every day. close close v. 动态 closed adj. 静态 示例 ...

September 21, 2021 · 3 min · Gray King

流利英语

tags: Learning English 连读 变音 /d/ + /j/ = /dʒj/ Would you like to try int on? /t/ + /j/ = /tʃj/ What about you? 词尾辅音 + 词首元音 It is A glass of water 还原 r RP her ideas Where is it? 语块切割 Chunking 语块(Chunk) 能表达实际含义且语义不割裂的词串。 语块切割(Chunking) 根据说话节奏将句子自然切割为若干语块。 语块语连读 同一语块内能连则连。 吞音 基本原则 同一语块内,音同则吞。 示例 Excuse me, Could you tell me how I can get to Pret A Monger? get to -> geto ...

September 21, 2021 · 1 min · Gray King

英语习语

tags: Learning English Give me a hand come in 有 come in all/different colors/size come on 「随意」鼓动、鼓励、催促 come to 总计 Excuse me 抱歉/引起注意 by the way/BTW 顺便说一下 shame on sb.! sb. 可耻 make it 成功达成 do/try one’s best (to do sth.) 尽最大努力做某事 sure thing no problem. 礼貌请求 礼貌程度 please > please 疑问句 > 肯定句 could > would > can 示例: Show me (please) Can you show me? Can you show me please? Would you show me (please)? Could you show me (please)? 适用场景 ...

September 20, 2021 · 2 min · Gray King

英语语法结构

tags: Learning English 双宾语 例句:I want to buy a birthday gift for my sister. 结构:buy sth. for sb. 双宾语:by sb. sth. buy my sister a birthday gift. Can I buy a drink for you? Can I buy you a drink? 双宾语限制 第二个宾语必须为名词,不能是人称代词(pron.)。 下面语句不能使用双宾语 I want to buy you it.(X) 双宾语动词 bring/give/tell/sell/ask/show Bring it to me Bring me a present. Give it to me Give me the pen. tell the story to me tell me the story email the photo to me email me the photo sell the handbag to her sell her the handbag ask sb. sth. show sb. sth. take the coffee to her: 不能使用 Give me the hand:习语不能使用 宾语从句 I think (that) … 在「一句简单句有且只有一个谓语动词」的基础上实现复杂句。 ...

September 20, 2021 · 3 min · Gray King

英语常用词

tags: Learning English seem 表示似乎 It seems to be very popular nowdays. 用作委婉 背景:the man in the photo。 对比以下两句 He is in good health He seems to be in good health(这句是错的 He seems in good health) 表示犹豫 That’s not right That doesn’t seem right That doesn’t seem to be right

September 20, 2021 · 1 min · Gray King

英语短语

tags: Learning English shape ʃeip be in great/good shape stay/keep in (good) shape 英语表示次数范围 five times a month once two weeks 英语表示尺码 loose /luːs/ 松的 tight /tait/ 紧的 what/how about 提议 What/How about some coffee? What/How about you? 穿衣:try on/take off/put on n.: try on sth I’d like to try on the shoes. pron.: try sth. on I’d like to try them on. think of 认为 sth. 怎么样 What do you think of my new shirt? What does she think of me? would like 委婉表示想要 do sth. I’d like to see some casual shirts. ...

September 20, 2021 · 2 min · Gray King

英语词性

tags: Learning English 副词 adv/adverb 是指在句子中表示行为或状态特征的词,用以修饰动词、形容词、其他副词或全句,表示时间、地点、程度、方式等概念。 副词可分为:时间副词、频率副词、地点副词、方式副词、程度副词、疑问副词、连接副词、关系副词、表顺序的副词以及表完成的副词。 频率副词 always usually often sometimes about 表示大约大约修饰数量。 形容词 adj 形容词后缀 -ful helpful useful thankful 形容词后缀 -ed interested excited 形容词后缀 -ing interesting exciting 动词 verb 情态动词 modal verb. can(could)/may(might)/must/need/to/shall(should)/will(would). 动名词 形式 v.-ing 动词的名词化。 语法:名词 语意:动词 形变规则 特殊 1 -e:去 e 加 ing live -> living give -> giving 特殊 2 短元音 + 一辅音:重复最后一个字母加 ing jog -> jogging swim -> swimming 常规:直接加 ing do -> doing study -> studying 词性 I usually go swimming. ...

September 20, 2021 · 4 min · Gray King

英语时态

tags: Learning English 通过动词变化来区分时间 通过动词变化来区分时间。 I am walking in the rain. 正在 I will walk in the rain. 将要 I walk in the rain sometings. 一般状态、重复、常态 一般现在时 表示: 当前的一般状态 重复或习惯动作 am/is/are(be 动词):是,处于某状态 do/does(实意动词):具体动作 (X): am/is/are + do/des 一般现在时不能 am/is/are 跟动词实意动词 一般现在时第三人称单音形规则 tags: 英语读音规则 一般现在时第三人称单数动词需要变形,需要注意变形后的读音 清对清 /s/ works helps 非清则浊 /z/ lives sees goes does /dʌz/ 组合 /dz/ /ts/ meets needs 近似音 -es /iz/ introduces fishes 现在进行时 当前正在发生的事情或动作,表示当前正在发生或者近将来。 I’m looking for a shirt. I’m not taking it off. Everyone is wearing the same shirt on the street! 结构 am/is/are doing ...

September 20, 2021 · 3 min · Gray King

Linux kernel

tags: Linux Linux I/O Linux I/O 演进 阻塞式:read()/write() 非阻塞式:select()/poll()/epoll(),不支持文件 I/O Thread Pool Direct I/O(数据软件):绕过 page cache 异步 IO(Linux AIO):早起进支持文件 I/O,近期支持了 epoll 支持非文件 I/O Linux io_uring [译] Linux 异步 I/O 框架 io_uring:基本原理、程序示例与性能压测 对比 Linux AIO: 重新设计实现真正的是不。 支持任何类型的 I/O:cached files、direct-access files 甚至 blocking sockets。 灵活、可扩展:基于 io_uring 能够重写 Linux 的每个系统调用。 原理及核心数据结构:SQ/CQ/SQE/CQE 每个 io_uring 实例都有两个环形队列,在内核和应用程序之间共享: 提交队列:submission queue(SQ) 完成队列:completion queue(CQ) 这两个队列: 都是单生产者、单消费者,size 是 2 的幂次; 提供无锁接口(lock-less access interface),内部使用内存屏障做同步(coordinated with memory barrers)。 使用方式: 请求 应用创建 SQ entries(SQE),更新 SQ tail; 内核消费 SQE,更新 SQ head 完成 内核为完成一个或多个请求创建 CQ enries(CQE),更新 CQ tail; 应用消费 CQE,更新 CQ head 完成事件(completion events)可能以任意顺序到达,到总是与特定的 SQE 相关联的。 消费 CQE 过程无需切换到内核态 带来的好处 支持批处理 支持文件 I/O 系统调用:read、write、send、recv、accept、opentat、stat、专用的一些系统调用,如 fallocate 不再局限于数据库应用 应对现在硬件架构:将硬件架构本身作为一个网络(多核多 CPU 是一个基础网络、CPU 之间是一个网络、CPU 和磁盘 I/O 之间又是一个网络) 三种工作模式 中断驱动模式(interrupt driven):默认模式。可通过 io_uring_enter() 提交 I/O 请求,然后直接检查 CQ 状态判断是否完成。 ...

September 7, 2021 · 1 min · Gray King

Scala lsp-metals

tags: Emacs,LSP 如果无法正常补全三方库,应该是 bloop 服务没有正常启动: 创建 ~/Library/Caches/org.scalameta.metals/bsp.trace.json 开启跟踪 查看项目目录下 metals.log

September 6, 2021 · 1 min · Gray King

领域模式

tags: DDD,《领域驱动设计》读书笔记 领域基础模式 模式:UBIQUITOUS LANGUAGE 在同领域专家、开发人员和项目管理沟通的过程中建立并使用 UBIQUITOUS LANGUAGE,,并在模型实现时依然使用 UBIQUITOUS LANGUAGE 来让设计与沟通相一致(中文语境下稍显困难),UBIQUITOUS LANGUAGE 让知识消化后直接驱动变更模型。 应用 UBIQUITOUS LANGUAGE 需要大声的建模。 模式:MODEL-DRIVEN DESIGN 严格按照模型来编写代码,让模型与实际系统相结合。 不再分离「分析模型」和程序设计,而是寻求一种能够满足这两方面需求的单一模型。 工具:面向对象编程语言、UML等。 更好的支持 UBIQUITOUS LANGUAGE. 模式:HANDS-ON MODELER 开发设计和模型设计紧密合作,避免模型设计者不参与编写和程序设计者不参与模型设计。 每一个开发人员都必须不同程度的参与模型讨论并且与领域专家保持联系,模型设计者及时通过 UBIQUITOUS LANGUAGE 与接触代码的人及时交换关于模型的想法。 领域模式构造块 模式:LAYERED ARCHITECTURE 分层架构是实现 DDD 的基础,分层架构将不同的层次的实现分开,自上倒下应分为: 用户界面层 应用层 领域层(模型的精髓) 基础设施层 核心在于要将领域层单独出来实现 MODEL-DRIVEN DESIGN,对业务进行建模封装业务规则。调用规则也只能自上而下的调用,不能反向调用。 领域层(或模型层)分离出来之后使得模型足够丰富,结构足够清晰,可以捕捉到基本的业务知识,并有效的使用这些知识。 模式:ENTITY 用于跟踪对象的状态,有唯一标识符,在系统中是可变的,两个对象是否一个通过唯一标识来判断,不是靠它们的属性定义。 模式:VALUE OBJECT 区别与 ENTITY ,没有唯一标识,仅记录状态,一般设计为不可变用于共享 VALUE OBJECT,两个对象是否一个通过对象属性的值来判断。 模式:SERVICE 没有状态,但又需要建模的对象,只包含动作。用于一些不适合建模为对象的领域概念。 与领域概念相关的操作不是 ENTITY 或 VALUE OBJECT 的一个自然组成部署 接口是根据领域模型的其他元素定义的。 操作是无状态的 模式:MODULE(或 PACKAGE) 根据对象的意义划分领域模型,低耦合高内聚。按照模式或者对象生命周期或者其他方式划分都是错误的。 模式:AGGREGATE 划分模型边界,统一对关联模型的创建、修改、复制和销毁。一般选定一个 ENTITY 对象作为 AGGREGATE 的「根」,同时对事务应用一组规则: ...

September 3, 2021 · 1 min · Gray King

Airflow

案例 Airflow powers AI。 Airflow SSO 接入 公司 SSO 系统不是基于开源标准,而是一套自定义的方式,目前网上没有成熟的解决方案,通过查看 Flask-AppBuilder 和 Airflow 的代码发现可以扩展 flask_appbuilder.security.views.AuthRemoteUserView 并通过自定义的 SecurityManager 指定 authremoteuserview 来实现,去掉具体 SSO 逻辑后的代码如下: from urllib.parse import urlencode from urllib.parse import urljoin import requests from flask import flash from flask import redirect from flask import request from flask_appbuilder.baseviews import expose from flask_appbuilder.security.views import AuthRemoteUserView try: from airflow.www.security import AirflowSecurityManager except ImportError: AirflowSecurityManager = None __version__ = "0.1.0" AUTHORIZE_URL = "https://example.com/sso/login" ACCESS_TOKEN_URL = "https://example.com/sso/check" class AuthComCasView(AuthRemoteUserView): def _get_redirect_uri(self): return urljoin(request.host_url, self.appbuilder.get_url_for_login) def get_authorize_params(self): return { "callback": self._get_redirect_uri(), } @expose("/login/") def login(self): token = request.args.get("token") if not token: params = self.get_authorize_params() redirect_uri = u"{}?{}".format( AUTHORIZE_URL, urlencode(params), ) return redirect(redirect_uri) data = self.exchange_token(token) if data["status"] < 0: flash("Invalid Token", "info") return "Invalid token" # Set REMOTE_USER to let user login request.environ["REMOTE_USER"] = data["username"] return super().login() @staticmethod def get_token_params(token): return { "token": token, } def exchange_token(self, token): data = self.get_token_params(token) return requests.get(ACCESS_TOKEN_URL, params=data).json() if AirflowSecurityManager is not None: class ComCasAirflowSecurityManager(AirflowSecurityManager): authremoteuserview = AuthComCasView 然后在 Airflow 的 webserver_config.py 中应用就行: ...

September 2, 2021 · 1 min · Gray King

Spark

tags: Bigdata Spark 编程语言选择 毋庸置疑,Python 应该是最简单也是大部分的选择,但是如果有依赖那么将要付出额外的心智负担(Spark 管理 Python 依赖)。 JVM 语言的依赖组织方式则具有天然的优势,可以将依赖(排除 Spark 生态之后)都 bundle 进 Jar 包里。 其中 Scala 兼具简单和 JVM 的优势,但是它「不流行」。 Spark Driver & Executor Driver 执行 spark-commit 客户端,创建 SparkContext 执行 main 函数。 Executor Spark Worker 上的线程 See also: Understanding the working of Spark Driver and Executor Cluster Mode Overview Spark 代码执行 我在配置 Spark 的时候就在好奇,从观察上看部分代码应该是执行在 Driver 上部分代码会执行在 Executer,这让我很好奇。 但是我通过学习 Spark RDD 学习到了一些知识。 以下代码是在 Executor 上执行的: Transformations 和 Actions 是执行在 Spark 集群的。 传递给 Transformations 和 Actions 的闭包函数也是执行在 Spark 集群上的。 其他额外的代码都是执行在 Driver 上的,所以想要在 Driver 打印日志需要上使用 collect: ...

August 27, 2021 · 2 min · Gray King

Scala

tags: Programming Language Scala 学习资源 Scala Book Scala 这么好的语言为什么不流行 HN:Scala 为什么不流行 Reddit:Scala 为什么不流行 结论:Java 人才更多且成本更低。 Scala 工具 sbt sbt new 无法处理替换过的 SSH 会导致 Auth fail,一个 workaround 就是手动 clone 项目然后: sbt new file:///path/to/template.g8 sbt 国内加速 ~/.sbt/repositories: [repositories] local nexus-aliyun:https://maven.aliyun.com/nexus/content/groups/public nexus-aliyun-ivy:https://maven.aliyun.com/nexus/content/groups/public/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext] typesafe: https://repo.typesafe.com/typesafe/ivy-releases/, [organization]/[module]/(scala_[scalaVersion]/)(sbt_[sbtVersion]/)[revision]/[type]s/[artifact](-[classifier]).[ext], bootOnly Unique Scala Rust from Scala Rust 和 Scala 有很多想通的地方,Rust 应该从 Scala 借鉴了很多: 可变量和不可变量 模式匹配 Trait 内置类型 val b: Byte = 1 val x: Int = 1 val l: Long = 1 val s: Short = 1 val d: Double = 2.0 val f: Float = 3.0 字符串拼接 Python 也支持类似的 f-string 语法,在 Scala 中是 s-string 语法。 ...

August 27, 2021 · 4 min · Gray King

SVG 绘制工具

https://inkscape.org/

August 25, 2021 · 1 min · Gray King

设计

SVG SVG 绘制工具

August 25, 2021 · 1 min · Gray King

Graphviz

Graphviz 教程 https://www2.eecs.berkeley.edu/Pubs/TechRpts/2013/EECS-2013-176.pdf Graphviz Examples https://graphviz.org/gallery/ Graphviz 绘制思维导图 Graphviz Online Tools 一个手绘风格的在线绘图工具:https://sketchviz.com/new Gaphviz Playground:http://magjac.com/graphviz-visual-editor/

August 24, 2021 · 1 min · Gray King

LeetCode: 98. Validate Binary Search Tree

tags: LeetCode https://leetcode.com/problems/validate-binary-search-tree/ /** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: bool isValidBST(TreeNode* root) { if (root == nullptr || (root->left == nullptr && root->right == nullptr)) { return true; } if (root->left != nullptr && root->right != nullptr) { if (root->left->val >= root->val || root->right->val <= root->val) { return false; } return isValidBST(root->left) && isValidBST(root->right); } if (root->left != nullptr) { if (root->left->val >= root->val) { return false; } return isValidBST(root->left); } if (root->right != nullptr) { if (root->right->val <= root->val) { return false; } return isValidBST(root->right) ; } return true; } }; 无法处理子树元素大于上一层的问题。中序遍历排序: ...

August 18, 2021 · 2 min · Gray King

LeetCode: 113. Path Sum II

tags: LeetCode,backtracking https://leetcode.com/problems/path-sum-ii/ /** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: vector<vector<int>> pathSum(TreeNode* root, int targetSum) { vector<vector<int>> r; if (root == nullptr) { return r; } if (root->left != nullptr) { auto left = pathSumSide(root-> left, root->val, targetSum); if (left.size() > 0) { left.insert(left.begin(), root->val); r.push_back(left); } } if (root->right != nullptr) { auto right = pathSumSide(root->right, root->val, targetSum); if (right.size() > 0) { right.insert(right.begin(), root->val); r.push_back(right); } } return r; } vector<int> pathSumSide(TreeNode* node, int sum, int targetSum) { vector<int> r; sum += node->val; if (node->left == nullptr && node->right == nullptr) { if (sum == targetSum) { r.push_back(node->val); return r; } } if (node->left != nullptr) { auto ret = pathSumSide(node->left, sum, targetSum); if (ret.size() > 0) { ret.insert(ret.begin(), node->val); return ret; } } if (node->right != nullptr) { auto ret = pathSumSide(node->right, sum, targetSum); if (ret.size() > 0) { ret.insert(ret.begin(), node->val); return ret; } } return r; } }; 失败的错误用例: ...

August 16, 2021 · 2 min · Gray King

LeetCode: 112. Path Sum

tags: LeetCode https://leetcode.com/problems/path-sum/ 递归版 /** * Definition for a binary tree node. * 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) {} * }; */ class Solution { public: bool hasPathSum(TreeNode* root, int targetSum) { if (root == nullptr) { return false; } return pathSum(root, 0, targetSum); } bool pathSum(TreeNode* node, int sum, int targetSum) { sum += node->val; if (node->left == nullptr && node->right == nullptr) { if (sum == targetSum) { return true; } } if (node->left != nullptr) { if (pathSum(node->left, sum, targetSum)) { return true; } } if (node->right != nullptr) { if (pathSum(node->right, sum, targetSum)) { return true; } } return false; } }; 测试用例 ...

August 16, 2021 · 2 min · Gray King