Boundary of Binary Tree — LeetCode 545 Python Solution
- Problem
- #545
- Pattern
- Tree Traversal
- Reading time
- 7 min
- Source
- leetcode.com
The problem
The boundary of a binary tree is the concatenation of the root, the left boundary, the leaves ordered from left-to-right, and the reverse order of the right boundary. The left boundary is the set of nodes defined by the following: The root node's left child is in the left boundary.
Example
- Input
- root = [1,null,2,3,4]
- Output
- [1,3,4,2]
- Explanation
- - The left boundary is empty because the root does not have a left child.
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 boundaryOfBinaryTree(self, root: Optional[TreeNode]) -> List[int]:
def dfs(nums: List[int], root: Optional[TreeNode], i: int):
if root is None:
return
if i == 0:
if root.left != root.right:
nums.append(root.val)
if root.left:
dfs(nums, root.left, i)
else:
dfs(nums, root.right, i)
elif i == 1:
if root.left == root.right:
nums.append(root.val)
else:
dfs(nums, root.left, i)
dfs(nums, root.right, i)
else:
if root.left != root.right:
nums.append(root.val)
if root.right:
dfs(nums, root.right, i)
else:
dfs(nums, root.left, i)
ans = [root.val]
if root.left == root.right:
return ans
left, leaves, right = [], [], []
dfs(left, root.left, 0)
dfs(leaves, root, 1)
dfs(right, root.right, 2)
ans += left + leaves + right[::-1]
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n), where n is the number of nodes in the binary tree auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 545. Boundary of 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 545. Boundary of Binary Tree?
- LeetCode 545. Boundary of Binary Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 545. Boundary of Binary Tree?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 545. Boundary of Binary Tree?
- The Python solution on this page uses O(n), where n is the number of nodes in the binary tree auxiliary space.
- What topics does LeetCode 545. Boundary of Binary Tree cover?
- LeetCode 545. Boundary of Binary Tree is tagged Tree, Depth-First Search and Binary Tree on LeetCode.
- Is LeetCode 545. Boundary of Binary Tree a premium problem?
- Yes. LeetCode 545. Boundary of Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.