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 }
|