Class Solution

java.lang.Object
g0601_0700.s0655_print_binary_tree.Solution

public class Solution extends Object
655 - Print Binary Tree.<p>Medium</p> <p>Given the <code>root</code> of a binary tree, construct a <strong>0-indexed</strong> <code>m x n</code> string matrix <code>res</code> that represents a <strong>formatted layout</strong> of the tree. The formatted layout matrix should be constructed using the following rules:</p> <ul> <li>The <strong>height</strong> of the tree is <code>height</code> and the number of rows <code>m</code> should be equal to <code>height + 1</code>.</li> <li>The number of columns <code>n</code> should be equal to <code>2<sup>height+1</sup> - 1</code>.</li> <li>Place the <strong>root node</strong> in the <strong>middle</strong> of the <strong>top row</strong> (more formally, at location <code>res[0][(n-1)/2]</code>).</li> <li>For each node that has been placed in the matrix at position <code>res[r][c]</code>, place its <strong>left child</strong> at <code>res[r+1][c-2&lt;sup&gt;height-r-1&lt;/sup&gt;]</code> and its <strong>right child</strong> at <code>res[r+1][c+2&lt;sup&gt;height-r-1&lt;/sup&gt;]</code>.</li> <li>Continue this process until all the nodes in the tree have been placed.</li> <li>Any empty cells should contain the empty string <code>&quot;&quot;</code>.</li> </ul> <p>Return <em>the constructed matrix</em> <code>res</code>.</p> <p><strong>Example 1:</strong></p> <p><img src="https://assets.leetcode.com/uploads/2021/05/03/print1-tree.jpg" alt="" /></p> <p><strong>Input:</strong> root = [1,2]</p> <p><strong>Output:</strong> [[&ldquo;&ldquo;,&ldquo;1&rdquo;,&rdquo;&rdquo;], [&ldquo;2&rdquo;,&ldquo;&ldquo;,&rdquo;&rdquo;]]</p> <p><strong>Example 2:</strong></p> <p><img src="https://assets.leetcode.com/uploads/2021/05/03/print2-tree.jpg" alt="" /></p> <p><strong>Input:</strong> root = [1,2,3,null,4]</p> <p><strong>Output:</strong> [[&ldquo;&ldquo;,&rdquo;&rdquo;,&ldquo;&ldquo;,&ldquo;1&rdquo;,&rdquo;&rdquo;,&ldquo;&ldquo;,&rdquo;&rdquo;], [&ldquo;&ldquo;,&ldquo;2&rdquo;,&rdquo;&rdquo;,&ldquo;&ldquo;,&rdquo;&rdquo;,&ldquo;3&rdquo;,&quot;&quot;], [&ldquo;&ldquo;,&rdquo;&rdquo;,&ldquo;4&rdquo;,&ldquo;&ldquo;,&rdquo;&rdquo;,&ldquo;&ldquo;,&rdquo;&rdquo;]]</p> <p><strong>Constraints:</strong></p> <ul> <li>The number of nodes in the tree is in the range <code>[1, 2<sup>10</sup>]</code>.</li> <li><code>-99 <= Node.val <= 99</code></li> <li>The depth of the tree will be in the range <code>[1, 10]</code>.</li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details