[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)

你可能感兴趣的:(algorithm,二叉树,leetcode,算法)