236. 二叉树的最近公共祖先

236. 二叉树的最近公共祖先

解法一: 后序遍历

go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 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 == p || root == q {
return root
}
leftNode := lowestCommonAncestor(root.Left, p, q)
rightNode := lowestCommonAncestor(root.Right, p, q)
if leftNode == nil {
return rightNode
} else if rightNode == nil {
return leftNode
}
return root
}
作者

wuhunyu

发布于

2024-02-09

更新于

2024-02-09

许可协议