From 2f514cd212303f53e8f30da93498b66e2df9577c Mon Sep 17 00:00:00 2001 From: X-shuffle <53906918+X-shuffle@users.noreply.github.com> Date: Wed, 16 Jun 2021 23:11:56 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00235.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=90=9C=E7=B4=A2=E6=A0=91=E7=9A=84=E6=9C=80=E8=BF=91=E5=85=AC?= =?UTF-8?q?=E5=85=B1=E7=A5=96=E5=85=88=20go=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 添加0235.二叉搜索树的最近公共祖先 go版本 --- ...35.二叉搜索树的最近公共祖先.md | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/problems/0235.二叉搜索树的最近公共祖先.md b/problems/0235.二叉搜索树的最近公共祖先.md index 15ff7af4..d78db42a 100644 --- a/problems/0235.二叉搜索树的最近公共祖先.md +++ b/problems/0235.二叉搜索树的最近公共祖先.md @@ -265,6 +265,54 @@ class Solution: else: return root ``` Go: +> BSL法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +//利用BSL的性质(前序遍历有序) +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + if root==nil{return nil} + if root.Val>p.Val&&root.Val>q.Val{//当前节点的值大于给定的值,则说明满足条件的在左边 + return lowestCommonAncestor(root.Left,p,q) + }else if root.Val 普通法 + +```go +/** + * Definition for a binary tree node. + * type TreeNode struct { + * Val int + * Left *TreeNode + * Right *TreeNode + * } + */ +//递归会将值层层返回 +func lowestCommonAncestor(root, p, q *TreeNode) *TreeNode { + //终止条件 + if root==nil||root.Val==p.Val||root.Val==q.Val{return root}//最后为空或者找到一个值时,就返回这个值 + //后序遍历 + findLeft:=lowestCommonAncestor(root.Left,p,q) + findRight:=lowestCommonAncestor(root.Right,p,q) + //处理单层逻辑 + if findLeft!=nil&&findRight!=nil{return root}//说明在root节点的两边 + if findLeft==nil{//左边没找到,就说明在右边找到了 + return findRight + }else {return findLeft} +} +``` +