算法面试-今日头条Android面试算法题-计算ViewGroup的深度

本文介绍了一个使用Kotlin编写的算法,用于计算ViewGroup的深度。通过递归方式遍历ViewGroup及其子View,计算出最深层次的深度。文章提供了不同深度的ViewGroup初始化示例,并展示了如何调用maxDeepthOfViewGroup函数来获取深度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

package interview

private fun maxDeepthOfViewGroup(view: View): Int {
    //如果没有孩子,这个节点的深度为0
    //如果有孩子,则是孩子深度+1
    if (view !is ViewGroup) {
        return 0
    }
    if (view.childs.isEmpty()) {
        return 0
    }
    var max = 0
    for (child in view.childs) {
        max = Math.max(max, maxDeepthOfViewGroup(child))
    }
    return max + 1
}

open class View(var id: Int) {
    open fun print() {
        println("I am view, id = ${id}")
    }
}

class ViewGroup(id: Int) : View(id) {
    var childs = ArrayList<View>()

    fun addView(view: View) {
        childs.add(view)
    }

    override fun print() {
        println("I am ViewGroup, id = ${id}")
    }
}

private fun initViewGroupDeepth1(): ViewGroup {
    var contentView = ViewGroup(0)
    return contentView
}

private fun initViewGroupDeepth2(): ViewGroup {

    var contentView = ViewGroup(0)

    var vg11 = ViewGroup(11)
    contentView.addView(vg11)
    contentView.addView(View(12))
    contentView.addView(View(13))

    return contentView
}

private fun initViewGroupDeepth3(): ViewGroup {

    var contentView = ViewGroup(0)

    var vg11 = ViewGroup(11)
    contentView.addView(vg11)
    contentView.addView(View(12))
    contentView.addView(View(13))

    var vg21 = ViewGroup(21)
    vg11.addView(vg21)

    return contentView
}

private fun initViewGroupDeepth4(): ViewGroup {

    var contentView = ViewGroup(0)

    var vg11 = ViewGroup(11)
    contentView.addView(vg11)
    contentView.addView(View(12))
    contentView.addView(View(13))

    var vg21 = ViewGroup(21)
    vg11.addView(vg21)


    vg21.addView(View(31))
    return contentView
}

fun main(args: Array<String>) {
    var contentView = initViewGroupDeepth1()
    println("maxDeepthOfViewGroup ${maxDeepthOfViewGroup(contentView)}")

    contentView = initViewGroupDeepth2()
    println("maxDeepthOfViewGroup ${maxDeepthOfViewGroup(contentView)}")

    contentView = initViewGroupDeepth3()
    println("maxDeepthOfViewGroup ${maxDeepthOfViewGroup(contentView)}")

    contentView = initViewGroupDeepth4()
    println("maxDeepthOfViewGroup ${maxDeepthOfViewGroup(contentView)}")
}

 

转载于:https://my.oschina.net/sfshine/blog/2958855

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值