其他分享
首页 > 其他分享> > 655. 输出二叉树

655. 输出二叉树

作者:互联网

655. 输出二叉树

给你一棵二叉树的根节点 root ,请你构造一个下标从 0 开始、大小为 m x n 的字符串矩阵 res ,用以表示树的 格式化布局 。构造此格式化布局矩阵需要遵循以下规则:

返回构造得到的矩阵res

 

 

示例 1:

输入:root = [1,2]
输出:
[["","1",""],
 ["2","",""]]

示例 2:

输入:root = [1,2,3,null,4]
输出:
[["","","","1","","",""],
 ["","2","","","","3",""],
 ["","","4","","","",""]]

 

提示:

矩阵构造完成,但是插入尝试未果,选择标答(dfs还是不够熟):

/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func calDepth(node *TreeNode) int {
    h := 0
    if node.Left != nil {
        h = calDepth(node.Left) + 1
    }
    if node.Right != nil {
        h = max(h, calDepth(node.Right)+1)
    }
    return h
}

func printTree(root *TreeNode) [][]string {
    height := calDepth(root)
    m := height + 1
    n := 1<<m - 1
    ans := make([][]string, m)
    for i := range ans {
        ans[i] = make([]string, n)
    }
    var dfs func(*TreeNode, int, int)
    dfs = func(node *TreeNode, r, c int) {
        ans[r][c] = strconv.Itoa(node.Val)
        if node.Left != nil {
            dfs(node.Left, r+1, c-1<<(height-r-1))
        }
        if node.Right != nil {
            dfs(node.Right, r+1, c+1<<(height-r-1))
        }
    }
    dfs(root, 0, (n-1)/2)
    return ans
}

func max(a, b int)  int {
    if b > a {
        return b
    }
    return a
}

 

标签:node,输出,TreeNode,res,矩阵,655,二叉树,root,节点
来源: https://www.cnblogs.com/fulaien/p/16611540.html