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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 

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()

    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) {
    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

你可能感兴趣的:(算法面试-今日头条Android面试算法题-计算ViewGroup的深度)