0x00 题目
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先
最近公共祖先表示为一个结点 n,满足 n 是 p、q 的祖先且 n 的深度尽可能大(一个节点也可以是它自己的祖先)
0x01 思路
要求 深度尽可能大
,选择 深度优先
的递归算法
先一口气跑到最底层,然后在回头
的时候进行判断处理
0x02 解法
解法
语言:Swift
树节点:TreeNode
public class TreeNode {
public var val: Int
public var left: TreeNode?
public var right: TreeNode?
public init() { self.val = 0; self.left = nil; self.right = nil; }
public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
self.val = val
self.left = left
self.right = right
}
}
递归方式:
func lowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? {
// 后面没路了,开始回头
if root == nil { return nil }
// 路上遇到目标了,转身回头
if (root === p || root === q) {
return root
}
// 先往左边找
let left = lowestCommonAncestor(root?.left, p, q)
// 回头了,找完左边,再往右边找
let right = lowestCommonAncestor(root?.right, p, q)
// 左边回头了,右边也回头了
if left != nil && right != nil {
// 既然左边有目标,右边也有目标,那“我”就是最终目标了
return root
}
if left == nil && right == nil {
// 既然左边没有目标,右边也没有目标,那“我”肯定不是目标了
return nil
}
// 目标在谁手上,就让谁回头
return left == nil ? right : left;
}
一款小巧的在线编译器
各种语言都有~