Print Binary Tree — LeetCode 655 Python Solution
- Problem
- #655
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of a binary tree, construct a 0-indexed m x n string matrix res that represents a formatted layout of the tree. The formatted layout matrix should be constructed using the following rules: The height of the tree is height and the number of rows m should be equal to height + 1.
Example
- Input
- root = [1,2]
- Output
- [["","1",""],
Python solution
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def printTree(self, root: Optional[TreeNode]) -> List[List[str]]:
def height(root):
if root is None:
return -1
return 1 + max(height(root.left), height(root.right))
def dfs(root, r, c):
if root is None:
return
ans[r][c] = str(root.val)
dfs(root.left, r + 1, c - 2 ** (h - r - 1))
dfs(root.right, r + 1, c + 2 ** (h - r - 1))
h = height(root)
m, n = h + 1, 2 ** (h + 1) - 1
ans = [[""] * n for _ in range(m)]
dfs(root, 0, (n - 1) // 2)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(V+E) |
| Space | O(V) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 655. Print Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 655. Print Binary Tree?
- LeetCode 655. Print Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 655. Print Binary Tree?
- The Python solution on this page runs in O(V+E).
- What is the space complexity of LeetCode 655. Print Binary Tree?
- The Python solution on this page uses O(V) auxiliary space.
- What topics does LeetCode 655. Print Binary Tree cover?
- LeetCode 655. Print Binary Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.