/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funclcaDeepestLeaves(root*TreeNode)*TreeNode{ifroot==nil{returnroot}varqueue[]*TreeNodeparents:=make(map[*TreeNode]*TreeNode)parents[root]=nilqueue=append(queue,root)forlen(queue)>0{cnt:=len(queue)vartmp[]*TreeNodefori:=0;i<cnt;i++{cur:=queue[i]ifcur.Left!=nil{tmp=append(tmp,cur.Left)parents[cur.Left]=cur}ifcur.Right!=nil{tmp=append(tmp,cur.Right)parents[cur.Right]=cur}}iflen(tmp)==0{break}else{queue=tmp}}findGrandfather:=func(left,right*TreeNode)(int,*TreeNode){weight:=0forparents[left]!=parents[right]{left,right=parents[left],parents[right]weight++}returnweight,parents[left]}ansWeight,ansNode:=math.MinInt32,queue[0]fori:=1;i<len(queue);i++{weight,grandfather:=findGrandfather(queue[i-1],queue[i])ifweight>ansWeight{ansWeight=weightansNode=grandfather}}returnansNode}
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/funclcaDeepestLeaves(root*TreeNode)*TreeNode{// dfs 返回如下两个结果
// 结果二为以 root 节点为根的二叉树的最深叶节点的最近公共祖先
// 结果一为以<结果二返回的节点>为根的二叉树的高度
vardfsfunc(root*TreeNode)(int,*TreeNode)dfs=func(root*TreeNode)(int,*TreeNode){ifroot==nil{return0,nil}lH,lAns:=dfs(root.Left)rH,rAns:=dfs(root.Right)iflH==rH{returnlH+1,root}elseiflH>rH{returnlH+1,lAns}else{// rH > lH
returnrH+1,rAns}}_,ans:=dfs(root)returnans}