545. Boundary of Binary Tree (Medium) - TengnanYao/daily_leetcode GitHub Wiki
# 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]:
# root
result = [root.val]
# left boundary
cur = root.left
while cur:
if cur.left or cur.right:
result.append(cur.val)
cur = cur.left or cur.right
# leaves
def dfs(node):
if node:
dfs(node.left)
if node != root and not node.left and not node.right:
result.append(node.val)
dfs(node.right)
dfs(root)
# right boundary
cur = root.right
temp = []
while cur:
if cur.left or cur.right:
temp = [cur.val] + temp
cur = cur.right or cur.left
return result + temp