From ddcd4ffba7a33bdbcfbb73538313952cfd95b2e4 Mon Sep 17 00:00:00 2001 From: guowenfeng <841784596@qq.com> Date: Mon, 2 Aug 2021 21:04:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=85=AC=E5=85=B1=E7=A5=96=E5=85=88=E7=9A=84?= =?UTF-8?q?=E7=89=B9=E5=AE=9A=E5=88=A4=E6=96=AD=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main.go" | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 "\347\262\276\351\200\211/04.08.\351\246\226\344\270\252\345\205\261\345\220\214\347\245\226\345\205\210/main.go" diff --git "a/\347\262\276\351\200\211/04.08.\351\246\226\344\270\252\345\205\261\345\220\214\347\245\226\345\205\210/main.go" "b/\347\262\276\351\200\211/04.08.\351\246\226\344\270\252\345\205\261\345\220\214\347\245\226\345\205\210/main.go" new file mode 100644 index 0000000..1b1352a --- /dev/null +++ "b/\347\262\276\351\200\211/04.08.\351\246\226\344\270\252\345\205\261\345\220\214\347\245\226\345\205\210/main.go" @@ -0,0 +1,30 @@ +package main + +type TreeNode struct { + Val int + Left *TreeNode + Right *TreeNode +} + +func lowestCommonAncestor(root *TreeNode, p *TreeNode, q *TreeNode) *TreeNode { + if root == nil { + return nil + } + + if root.Val == p.Val || root.Val == q.Val { + return root + } + + lNode := lowestCommonAncestor(root.Left, p, q) + rNode := lowestCommonAncestor(root.Right, p, q) + + if lNode != nil && rNode != nil { + return root + } + + if lNode == nil { + return rNode + } + + return lNode +}