KatInterview

545. Boundary of Binary Tree

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the boundary of a binary tree, which is a specific sequence of nodes. The boundary is composed of four parts concatenated in order:

Solution

Boundary of Binary Tree in Python

# 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]:
        if not root:
            return []

        res = []

        def is_leaf(node):
            return node and not node.left and not node.right

        # Add root if it's not a leaf. If it is, it's a single-node tree.
        if not is_leaf(root):
            res.append(root.val)
        else:
            res.append(root.val)
            return res

        # 1. Add left boundary
        def add_left_boundary(node):
            if not node or is_leaf(node):
                return
            res.append(node.val)
            if node.left:
                add_left_boundary(node.left)
            else:
                add_left_boundary(node.right)

        add_left_boundary(root.left)

        # 2. Add leaves
        def add_leaves(node):
            if not node:
                return
            if is_leaf(node):
                res.append(node.val)
                return
            add_leaves(node.left)
            add_leaves(node.right)

        add_leaves(root)

        # 3. Add right boundary
        def add_right_boundary(node):
            if not node or is_leaf(node):
                return
            if node.right:
                add_right_boundary(node.right)
            else:
                add_right_boundary(node.left)
            res.append(node.val) # Post-order addition for reverse order

        add_right_boundary(root.right)

        return res

Boundary of Binary Tree in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<Integer> boundaryOfBinaryTree(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }

        // Add root if it's not a leaf. If it is a leaf, it's a single-node tree.
        if (!isLeaf(root)) {
            res.add(root.val);
        } else {
            res.add(root.val);
            return res;
        }

        // 1. Add left boundary (excluding leaves)
        addLeftBoundary(root.left, res);

        // 2. Add all leaf nodes
        addLeaves(root, res);

        // 3. Add right boundary in reverse order (excluding leaves)
        addRightBoundary(root.right, res);

        return res;
    }

    private boolean isLeaf(TreeNode node) {
        return node != null && node.left == null && node.right == null;
    }

    // Adds non-leaf nodes on the left boundary path.
    private void addLeftBoundary(TreeNode node, List<Integer> res) {
        if (node == null || isLeaf(node)) {
            return;
        }
        res.add(node.val);
        if (node.left != null) {
            addLeftBoundary(node.left, res);
        } else {
            addLeftBoundary(node.right, res);
        }
    }

    // Adds all leaf nodes from left to right.
    private void addLeaves(TreeNode node, List<Integer> res) {
        if (node == null) {
            return;
        }
        if (isLeaf(node)) {
            res.add(node.val);
            return;
        }
        addLeaves(node.left, res);
        addLeaves(node.right, res);
    }

    // Adds non-leaf nodes on the right boundary path in reverse order.
    private void addRightBoundary(TreeNode node, List<Integer> res) {
        if (node == null || isLeaf(node)) {
            return;
        }
        if (node.right != null) {
            addRightBoundary(node.right, res);
        } else {
            addRightBoundary(node.left, res);
        }
        // Add node value after recursion to get reverse order
        res.add(node.val);
    }
}

Boundary of Binary Tree in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> boundaryOfBinaryTree(TreeNode* root) {
        if (!root) {
            return {};
        }

        vector<int> res;
        // Add root node if it is not a leaf.
        // If root is a leaf, it will be handled by the leaf traversal.
        // A single-node tree is a special case. The root is the boundary.
        if (!isLeaf(root)) {
            res.push_back(root->val);
        } else {
            res.push_back(root->val);
            return res;
        }

        // 1. Add left boundary
        addLeftBoundary(root->left, res);

        // 2. Add leaves
        addLeaves(root, res);

        // 3. Add right boundary in reverse
        addRightBoundary(root->right, res);

        return res;
    }

private:
    bool isLeaf(TreeNode* node) {
        return node && !node->left && !node->right;
    }

    // Pre-order traversal to find left boundary
    void addLeftBoundary(TreeNode* node, vector<int>& res) {
        if (!node || isLeaf(node)) {
            return;
        }
        res.push_back(node->val);
        if (node->left) {
            addLeftBoundary(node->left, res);
        } else {
            addLeftBoundary(node->right, res);
        }
    }

    // Pre-order traversal to find leaves
    void addLeaves(TreeNode* node, vector<int>& res) {
        if (!node) {
            return;
        }
        if (isLeaf(node)) {
            res.push_back(node->val);
            return;
        }
        addLeaves(node->left, res);
        addLeaves(node->right, res);
    }

    // Post-order traversal to find right boundary
    void addRightBoundary(TreeNode* node, vector<int>& res) {
        if (!node || isLeaf(node)) {
            return;
        }
        if (node->right) {
            addRightBoundary(node->right, res);
        } else {
            addRightBoundary(node->left, res);
        }
        res.push_back(node->val);
    }
};

Boundary of Binary Tree in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function boundaryOfBinaryTree(root: TreeNode | null): number[] {
    if (!root) {
        return [];
    }

    const res: number[] = [];

    const isLeaf = (node: TreeNode | null): boolean => {
        return !!node && !node.left && !node.right;
    };

    // Add root if it's not a leaf. If it is, it's a single-node tree.
    if (!isLeaf(root)) {
        res.push(root.val);
    } else {
        res.push(root.val);
        return res;
    }

    // 1. Add left boundary
    const addLeftBoundary = (node: TreeNode | null) => {
        if (!node || isLeaf(node)) {
            return;
        }
        res.push(node.val);
        if (node.left) {
            addLeftBoundary(node.left);
        } else {
            addLeftBoundary(node.right);
        }
    };

    addLeftBoundary(root.left);

    // 2. Add leaves
    const addLeaves = (node: TreeNode | null) => {
        if (!node) {
            return;
        }
        if (isLeaf(node)) {
            res.push(node.val);
            return;
        }
        addLeaves(node.left);
        addLeaves(node.right);
    };

    addLeaves(root);

    // 3. Add right boundary
    const addRightBoundary = (node: TreeNode | null) => {
        if (!node || isLeaf(node)) {
            return;
        }
        if (node.right) {
            addRightBoundary(node.right);
        } else {
            addRightBoundary(node.left);
        }
        res.push(node.val); // Add after recursion for reverse order
    };

    addRightBoundary(root.right);

    return res;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.