1
0
mirror of https://gitee.com/coder-xiaomo/leetcode-problemset synced 2025-01-10 18:48:13 +08:00
Code Issues Projects Releases Wiki Activity GitHub Gitee
leetcode-problemset/leetcode-cn/problem (Chinese)/输出二叉树 [print-binary-tree].html

46 lines
2.0 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<p>给你一棵二叉树的根节点 <code>root</code> ,请你构造一个下标从 <strong>0</strong> 开始、大小为 <code>m x n</code> 的字符串矩阵 <code>res</code> ,用以表示树的 <strong>格式化布局</strong> 。构造此格式化布局矩阵需要遵循以下规则:</p>
<ul>
<li>树的 <strong>高度</strong><code>height</code> ,矩阵的行数 <code>m</code> 应该等于 <code>height + 1</code></li>
<li>矩阵的列数 <code>n</code> 应该等于 <code>2<sup>height+1</sup> - 1</code></li>
<li><strong>根节点</strong> 需要放置在 <strong>顶行</strong><strong>正中间</strong> ,对应位置为 <code>res[0][(n-1)/2]</code></li>
<li>对于放置在矩阵中的每个节点,设对应位置为 <code>res[r][c]</code> ,将其左子节点放置在 <code>res[r+1][c-2<sup>height-r-1</sup>]</code> ,右子节点放置在 <code>res[r+1][c+2<sup>height-r-1</sup>]</code></li>
<li>继续这一过程,直到树中的所有节点都妥善放置。</li>
<li>任意空单元格都应该包含空字符串 <code>""</code></li>
</ul>
<p>返回构造得到的矩阵<em> </em><code>res</code></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><strong>示例 1</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" style="width: 141px; height: 181px;" />
<pre>
<strong>输入:</strong>root = [1,2]
<strong>输出:</strong>
[["","1",""],
&nbsp;["2","",""]]
</pre>
<p><strong>示例 2</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" style="width: 207px; height: 302px;" />
<pre>
<strong>输入:</strong>root = [1,2,3,null,4]
<strong>输出:</strong>
[["","","","1","","",""],
&nbsp;["","2","","","","3",""],
&nbsp;["","","4","","","",""]]
</pre>
<p>&nbsp;</p>
<p><strong>提示:</strong></p>
<ul>
<li>树中节点数在范围 <code>[1, 2<sup>10</sup>]</code></li>
<li><code>-99 &lt;= Node.val &lt;= 99</code></li>
<li>树的深度在范围 <code>[1, 10]</code></li>
</ul>