← 返回 snowflake 的题目列表Boundary of Binary Tree
类型:qbank
Given the root of a binary tree, return the values of its boundary in anti-clockwise direction starting from the root.
Boundary of Binary Tree
Given the root of a binary tree, return the values of its boundary in anti-clockwise direction starting from the root.
SWE
tree
dfs
tree-traversal
medium
Frequency
Single report
Last asked
2025-12-06
Stage
phone-screen · onsite-coding
Boundary of Binary Tree
Problem Requirements
You are given the root of a binary tree. Your goal is to return a list of values representing the boundary of the tree. You must trace this boundary in an anti-clockwise (counter-clockwise) direction, starting from the root.
The boundary consists of four specific parts:
The Root: The top node of the tree.
The Left Boundary: The nodes along the left edge. Note: Do not include leaf nodes (nodes with no children) in this part.
The Leaves: All the bottom nodes that have no children, listed from left to right.
The Right Boundary: The nodes along the right edge. Note: These are added in reverse order (bottom to top) and do not include leaf nodes.
Special Rule: If the root node has no left or right subtree (it has no children), then the boundary is just the root itself.
Test Cases
Case 1:
Input: root = [1,null,2,3,4]
Output: [1,3,4,2]
Case 2:
Input: root = [1,2,3,4,5,6,null,null,null,7,8,9,10]
Output: [1,2,4,7,8,9,10,6,3]
Technical Constraints
Tree Size: The number of nodes is between 1 and 10^4 (10,000).
Value Range: Each Node.val is between -1000 and 1000.