黄哥Go语言,LeetCode 965题 Univalued Binary Tree解题思路

159 阅读1分钟
原文链接: zhuanlan.zhihu.com

早起刷一个水题,LeetCode 965题 Univalued Binary Tree

Loading...leetcode.com图标

解题思路:

1、先dfs 遍历生成一个所有node的值slice 表。

2、遍历这个slice 和 root 的Val 值比较,如果不相等返回false,如果循环结束,返回true

代码如下:

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func isUnivalTree(root *TreeNode) bool {
    if root == nil {
        return true
    }
    rootVal := root.Val
    var allNodeValues []int
    dfs(root, &allNodeValues)
    for _, val := range allNodeValues{
        if val != rootVal {
            return false
        }
    }
    return true
}

func dfs(root *TreeNode, allNodeValues *[]int){
    if root != nil {
        *allNodeValues = append(*allNodeValues, root.Val)
        dfs(root.Left, allNodeValues)
        dfs(root.Right, allNodeValues)
    }
}

黄哥Go 语言培训大纲

pythonpeixun/articlegithub.com图标