[Leetcode] 545. Boundary of Binary Tree 二叉树的边界

思路

There are three parts in the result, left boundary, right boundary, and leaf nodes.
left boundary and right boundary can use a while loop from root till the leaf.
For leaf nodes, we can not use common level order traverse, because leaf nodes may appear in different levels. We need to modify the level order traverse process. In order to make the leaves in the order from left to right, we can pop node from right in the queue, and get a reversed leaf array.
space complexity: O(n); time complexity: O(n)

# 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: TreeNode) -> List[int]:
        if not root:
            return []
        leaves = self.get_leaves(root)
        left_by = []
        right_by = []
        left = root.left
        right = root.right
        while left and (left.left or left.right): # get left boundary
            left_by.append(left.val)
            if left.left:
                left = left.left
            else:
                left = left.right
        while right and (right.left or right.right): # get right boundary
            right_by.append(right.val)
            if right.right:
                right = right.right
            else:
                right = right.left
        res = [root.val]
        if left_by:
            res += left_by
        if leaves and (root.left or root.right):
            res += [node.val for node in leaves]
        if right_by:
            res += reversed(right_by)
        return res
             
    def get_leaves(self, root): # get leaves, make sure they are in right order
        queue = deque([root])
        leaves = []
        while queue:
            node = queue.pop()
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
            if not node.left and not node.right:
                leaves.append(node)
        return reversed(leaves)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值