lowestCommonAncestor
|Word Count:125|Reading Time:1mins|Post Views:
力扣每日一题
- Lowest Common Ancestor of Deepest Leaves
很典型的一个树相关的题,倒序解,但其实解完我也不是很理解题意。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| func lcaDeepestLeaves(root *TreeNode) *TreeNode { if root.Left == nil && root.Right == nil { return root }
var postorder func(*TreeNode) (*TreeNode, int) postorder = func(node *TreeNode) (*TreeNode, int) { if node == nil { return nil, 0 } l, lDepth := postorder(node.Left) r, rDepth := postorder(node.Right)
if lDepth == rDepth { return node, lDepth + 1 } else if lDepth > rDepth { return l, lDepth + 1 } else { return r, rDepth + 1 } }
res, _ := postorder(root) return res }
|