655. Print Binary Tree

复制代码
package LeetCode_655

/**
 * 655. Print Binary Tree
 * https://leetcode.com/problems/print-binary-tree/description/
 * Example 1:
Input:
1
/
2
Output:
[["", "1", ""],
["2", "", ""]]
 * */

class TreeNode(var `val`: Int) {
    var left: TreeNode? = null
    var right: TreeNode? = null
}

class Solution {
    fun printTree(root: TreeNode?): List<List<String>> {
        //get height and width
        val h = getHeight(root)
        val w = (1 shl h) - 1//2^h-1
        //print by h and w
        val result = ArrayList<ArrayList<String>>()
        //init
        for (i in 0 until h) {
            val list = ArrayList<String>()
            for (j in 0 until w) {
                list.add("")
            }
            result.add(list)
        }
        fill(root, result, 0, 0, w - 1)
        return result
    }

    private fun fill(node: TreeNode?, result: ArrayList<ArrayList<String>>, height: Int, l: Int, r: Int) {
        if (node == null) {
            return
        }
        val mid = (l + r) / 2
        result[height][mid] = node.`val`.toString()
        fill(node.left, result, height + 1, l, mid - 1)
        fill(node.right, result, height + 1, mid + 1, r)
    }

    private fun getHeight(node: TreeNode?): Int {
        if (node == null) {
            return 0
        }
        return Math.max(getHeight(node.left), getHeight(node.right)) + 1
    }
}
复制代码

 

posted @   johnny_zhao  阅读(103)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示