春招打卡|二叉树的堂兄弟节点|go实现

257 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

一、题目描述

在二叉树中,根节点位于深度 0 处,每个深度为 k 的节点的子节点位于深度 k+1 处。如果二叉树的两个节点深度相同,但 父节点不同 ,则它们是一对堂兄弟节点。我们给出了具有唯一值的二叉树的根节点 root ,以及树中两个不同节点的值 x 和 y 。只有与值 x 和 y 对应的节点是堂兄弟节点时,才返回 true 。否则,返回 false。

图片.png

输入:root = [1,2,3,4], x = 4, y = 3 输出:false

二、思路分析

  • 堂兄弟节点,是深度相同,父节点不同的节点。在深度优先遍历的基础上,加入深度和父节点两个参数。函数原型
var dfs func(node,parent *TreeNode,depth int)
  • 递归终止条件,node为空
if node == nil {
	return 
}
  • 找到node.Val的值等于x时,将全局变量xdepth与xparent 赋值为depth和parent,如果等于y则进行,相同操作。赋值的全局xdepth和xparent用于后续进行堂兄弟节点判断。
  • 调用时传入root,父节点为nil,深度为0,每次递归进入子节点,传入当前节点为父节点,深度加一。
  • 最后全局变量xparent 不等于yparent 并且xdepth等于ydepth,则x和y是堂兄弟节点。

三、AC 代码

func isCousins(root *TreeNode, x int, y int) bool {
    var xdepth,ydepth int
    var xparent,yparent *TreeNode
    var dfs func(node *TreeNode,parent *TreeNode,depth int)
    dfs = func(node *TreeNode,parent *TreeNode,depth int) {
        if node == nil {
            return
        }
        if node.Val == x {
            xdepth,xparent = depth,parent
        }else if node.Val == y {
            ydepth,yparent = depth,parent
        }
        dfs(node.Left,node,depth+1)
        dfs(node.Right,node,depth+1)
    }
    dfs(root,nil,0)
    return xparent != yparent && xdepth == ydepth
}

四、总结

一道简单题目,可以加入xfound与yfound优化dfs过程,如果找到 x,y两个堂兄弟节点,则直接返回。

if node.Val == x {
            xdepth,xparent,xfound= depth,parent,true
        }else if node.Val == y {
            ydepth,yparent,yfound = depth,parent,true
        }
}

if xfound && yfound {
	return
}