Boundary of Binary Tree

Pattern: Views and boundaries

medium

The boundary is the root, then the left edge going down (without leaves), then every leaf from left to right, then the right edge going up (without leaves). Each part is a simple walk; leaves are only counted in the middle part.

The problem

Return the boundary of a binary tree anticlockwise from the root: the root, the left boundary (top down, leaves excluded), all leaves left to right, then the right boundary (bottom up, leaves excluded). The left boundary follows left children, or a right child when there is no left; the right boundary is the mirror. The example gives [1, 2, 4, 7, 8, 9, 10, 6, 3]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What are the three parts?
  • Which nodes could be counted twice?
  • How does the left edge continue when a node has no left child?

Hints

    Brute force, and why it fails

    Collect every node with its depth and position and filter: possible, but much harder to get right.

    The key insight

    Splitting the outline into three simple walks, and letting only the middle one take leaves, gives each node at most once.

    Dry run

    out1 2

    Tree [1, 2, 3, 4, 5, 6, null, null, null, 7, 8, 9, 10]. Root 1. Left edge: 2 (4 is a leaf, so it stops).

    Step 1 of 3

    The plan

    out = [root] (if root is not a leaf)
    left edge: n = root.left; while n: if not leaf: add; n = n.left or n.right
    leaves: preorder, add leaves
    right edge: same from root.right with right first; add reversed
    

    Complexity

    Time
    O(n)
    Space
    O(h)

    Each part is at most one walk over the tree.

    Edge cases

    • Only a root: [root].
    • No left subtree: the left boundary is empty.
    • A root with one leaf child.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public List<Integer> boundaryOfBinaryTree(TreeNode root) {
            List<Integer> out = new ArrayList<>();
            if (root == null) return out;
            out.add(root.val);
            if (isLeaf(root)) return out;
            for (TreeNode n = root.left; n != null; n = n.left != null ? n.left : n.right)   // left edge, top down
                if (!isLeaf(n)) out.add(n.val);
            addLeaves(root, out);                                                              // leaves, left to right
            List<Integer> right = new ArrayList<>();
            for (TreeNode n = root.right; n != null; n = n.right != null ? n.right : n.left)   // right edge ...
                if (!isLeaf(n)) right.add(n.val);
            Collections.reverse(right);                                                        // ... bottom up
            out.addAll(right);
            return out;
        }
    
        private boolean isLeaf(TreeNode n) {
            return n.left == null && n.right == null;
        }
    
        private void addLeaves(TreeNode n, List<Integer> out) {
            if (n == null) return;
            if (isLeaf(n)) { out.add(n.val); return; }
            addLeaves(n.left, out);
            addLeaves(n.right, out);
        }
    }

    C++

    class Solution {
    public:
        vector<int> boundaryOfBinaryTree(TreeNode* root) {
            vector<int> out;
            if (root == NULL) return out;
            out.push_back(root->val);
            if (isLeaf(root)) return out;
            for (TreeNode* n = root->left; n != NULL; n = n->left != NULL ? n->left : n->right)     // left edge, top down
                if (!isLeaf(n)) out.push_back(n->val);
            addLeaves(root, out);                                                                   // leaves, left to right
            vector<int> right;
            for (TreeNode* n = root->right; n != NULL; n = n->right != NULL ? n->right : n->left)   // right edge ...
                if (!isLeaf(n)) right.push_back(n->val);
            out.insert(out.end(), right.rbegin(), right.rend());                                    // ... bottom up
            return out;
        }
    
        bool isLeaf(TreeNode* n) {
            return n->left == NULL && n->right == NULL;
        }
    
        void addLeaves(TreeNode* n, vector<int>& out) {
            if (n == NULL) return;
            if (isLeaf(n)) { out.push_back(n->val); return; }
            addLeaves(n->left, out);
            addLeaves(n->right, out);
        }
    };

    Python

    class Solution:
        def boundaryOfBinaryTree(self, root) -> list[int]:
            if not root:
                return []
            is_leaf = lambda n: not n.left and not n.right
            if is_leaf(root):
                return [root.val]
            out, n = [root.val], root.left
            while n:                                # left edge, top down
                if not is_leaf(n):
                    out.append(n.val)
                n = n.left or n.right
    
            def leaves(n):                          # leaves, left to right
                if n:
                    if is_leaf(n):
                        out.append(n.val)
                    leaves(n.left)
                    leaves(n.right)
    
            leaves(root)
            right, n = [], root.right
            while n:                                # right edge ...
                if not is_leaf(n):
                    right.append(n.val)
                n = n.right or n.left
            return out + right[::-1]                # ... bottom up

    Common mistakes

    • Adding a leaf twice.
    • Adding the right edge top down.

    Similar problems