Leetcode 655: Print Binary Tree

grid47
grid47
Exploring patterns and algorithms
Sep 2, 2024 7 min read

A binary tree where nodes are printed visually, with the structure softly glowing as it is printed.
Solution to LeetCode 655: Print Binary Tree Problem

Given the root of a binary tree, construct a matrix representation of the tree using specific formatting rules to place each node in the appropriate position in the matrix.
Problem
Approach
Steps
Complexity
Input: The input is the root of a binary tree represented as an array of nodes.
Example: root = [10, 5, 15, null, 7]
Constraints:
• The number of nodes in the tree is in the range [1, 210].
• -99 <= Node.val <= 99
• The depth of the tree will be in the range [1, 10].
Output: The output is a 0-indexed matrix representing the binary tree, formatted according to the specified rules.
Example: [['', '', '10', '', ''], ['', '5', '', '15', ''], ['', '', '', '7', '']]
Constraints:
• The output matrix will be of size m x n, where m is the height of the tree + 1 and n is 2^height + 1 - 1.
Goal: The goal is to recursively place each node in its appropriate position in the matrix based on the rules provided.
Steps:
• 1. Calculate the height of the tree.
• 2. Calculate the width of the matrix using the tree height.
• 3. Recursively place the root node and its children in the matrix.
• 4. Fill in the left and right children by adjusting their positions accordingly in each row.
Goal: The tree will have a depth between 1 and 10, with node values between -99 and 99, and there will be no more than 210 nodes.
Steps:
• 1 <= number of nodes <= 210
• -99 <= Node.val <= 99
• Tree depth between 1 and 10
Assumptions:
• The input will always be a valid binary tree with nodes having unique values.
Input: root = [10, 5, 15, null, 7]
Explanation: The root node `10` is placed in the center of the matrix. Its children, `5` and `15`, are placed in subsequent rows, with `7` placed as the child of `15`.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus