首页 > 其他 > 详细

Daily Coding Problem: Problem #954

时间:2021-08-02 14:51:41      阅读:28      评论:0      收藏:0      [点我收藏+]
/**
 * This problem was asked by Google.
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival subtrees:
    0
   /   1   0
     /     1   0
   /   1   1
 * */

class Node(value_: Int) {
    var value = value_
    var left: Node? = null
    var right: Node? = null
}

class Problem_954 {
    /**
     * solution: check whether if unival tree:
     * 1. leaf node
     * 2. children node has save value
     * */

    fun countUnivalTree(root:Node?):Int{
        return helperCount(root)
    }

    private fun helperCount(node:Node?):Int{
        if (node == null){
            return 0
        }
        if (node.left==null && node.right==null){
            return 1
        }
        var count = 0
        if (node.left?.value == node.right?.value){
            count++
        }
        if (node.left!=null){
            count += helperCount(node.left!!)
        }
        if (node.right!=null){
            count += helperCount(node.right!!)
        }
        return count
    }
}

 

Daily Coding Problem: Problem #954

原文:https://www.cnblogs.com/johnnyzhao/p/15089413.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!