/** * Definition for a binary tree node. * public class TreeNode { * public var val: Int * public var left: TreeNode? * public var right: TreeNode? * public init(_ val: Int) { * self.val = val * self.left = nil * self.right = nil * } * } */
classSolution{ funclowestCommonAncestor(_ root: TreeNode?, _ p: TreeNode?, _ q: TreeNode?) -> TreeNode? { for pp in rewalk(root, p) { for qq in rewalk(root, q) { if pp?.val == qq?.val { return pp } } } returnnil }
funcrewalk(_ root: TreeNode?, _ node: TreeNode?) -> [TreeNode?] { if root ==nil { return [TreeNode?]() } if root?.left?.val == node?.val || root?.right?.val == node?.val { return [node, root] } var rl = rewalk(root?.left, node) if rl.count >1 { rl.append(root) return rl } var rr = rewalk(root?.right, node) if rr.count >1 { rr.append(root) return rr } return [node] } }
funclowestCommonAncestor(root, p, q *TreeNode) *TreeNode { cp := make(chan *TreeNode) cq := make(chan *TreeNode) go rewalk(root, p, cp) go rewalk(root, q, cq)
ans := make(chan *TreeNode)
gofunc() { ap := []*TreeNode{} aq := []*TreeNode{} for { select { case p := <- cp: for _, q := range aq { if p == q { ans <- p } } ap = append(ap, p) case q := <- cq: for _, p := range ap { if q == p { ans <- q } } aq = append(aq, q) } } }()
return <-ans }
funcrewalk(root, node *TreeNode, ch chan *TreeNode)bool { if root == nil { returnfalse } if root.Left == node || root.Right == node { ch <- node ch <- root returntrue } if r := rewalk(root.Left, node, ch); r { ch <- root returntrue } if r := rewalk(root.Right, node, ch); r { ch <- root returntrue } ch <- node returnfalse }