Given the root
of a binary tree, you need to construct a 2D list that contains the values of the tree nodes in a specific format. The format for constructing the 2D list is as follows:
height
.2^height - 1
.""
.""
.class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def printTree(root: TreeNode):
# Function to compute the height of the tree
def getHeight(node):
if not node:
return 0
return 1 + max(getHeight(node.left), getHeight(node.right))
# Function to fill the 2D list
def fill(res, node, row, left, right):
if not node:
return
mid = (left + right) // 2
res[row][mid] = str(node.val)
fill(res, node.left, row + 1, left, mid - 1)
fill(res, node.right, row + 1, mid + 1, right)
# Step 1: Compute the height of the tree
height = getHeight(root)
# Step 2: Initialize the 2D list
width = (2 ** height) - 1
res = [["" for _ in range(width)] for _ in range(height)]
# Step 3: Fill the 2D list with tree nodes
fill(res, root, 0, 0, width - 1)
return res
getHeight
function computes the height of the tree by recursively finding the maximum height between the left and right subtrees and adding 1 for the current node.height
) is used to determine the number of rows.2^height - 1
.res
is initialized with ""
in all cells.fill
function places each node value in the correct position.left
and right
is where the current node’s value should be placed.O(N)
, where N
is the number of nodes in the tree.O(N)
.O(N)
.This approach ensures that each node is correctly positioned within the constraints of the specified 2D list format.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?