545 Boundary of Binary Tree

Given a binary tree, return the values of its boundary in anti-clockwise direction starting from root. Boundary includes left boundary, leaves, and right boundary in order without duplicate nodes.

Left boundary is defined as the path from root to the left-most node. Right boundary is defined as the path from root to the right-most node. If the root doesn't have left subtree or right subtree, then the root itself is left boundary or right boundary. Note this definition only applies to the input binary tree, and not applies to any subtrees.

Theleft-mostnode is defined as aleafnode you could reach when you always firstly travel to the left subtree if exists. If not, travel to the right subtree. Repeat until you reach a leaf node.

Theright-mostnode is also defined by the same way with left and right exchanged.

Example 1

Input:

  1
   \
    2
   / \
  3   4


Ouput:

[1, 3, 4, 2]


Explanation:

The root doesn't have left subtree, so the root itself is left boundary.
The leaves are node 3 and 4.
The right boundary are node 1,2,4. Note the anti-clockwise direction means you should output reversed right boundary.
So order them in anti-clockwise without duplicates and we have [1,3,4,2].

Example 2

Input:

    ____1_____
   /          \
  2            3
 / \          / 
4   5        6   
   / \      / \
  7   8    9  10  


Ouput:

[1,2,4,7,8,9,10,6,3]


Explanation:

The left boundary are node 1,2,4. (4 is the left-most node according to definition)
The leaves are node 4,7,8,9,10.
The right boundary are node 1,3,6,10. (10 is the right-most node).
So order them in anti-clockwise without duplicate nodes we have [1,2,4,7,8,9,10,6,3].

**Note: not Currently working

The Idea: I first run a level order traversal to collect all the nodes, along with an indicator whether or not the node was right or left. The solution follows to be the root element as the first node, and every intermediate level as the first and last nodes displaced at the front and back respectfully in the final array. Finally the last level will displace all it's nodes (much like the root).

The problem is that a tree like this which contains node (5), that the algorithm completely ignores.

Complexity: O(n) time, O(n) space

vector<int> boundaryOfBinaryTree(TreeNode* root) {
    if (!root) return vector<int>();

    // store level order traversal
    queue<pair<TreeNode*, bool>> q_isRight;
    q_isRight.push({ root, false });
    q_isRight.push({ nullptr, false });

    vector<vector<pair<int, bool>>> level_order;
    vector<pair<int, bool>> cur_level_order;

    while (!q_isRight.empty()) {
        pair<TreeNode*, bool> cur_elm = q_isRight.front(); q_isRight.pop();

        if (cur_elm.first) {
            cur_level_order.push_back({ cur_elm.first->val, cur_elm.second });

            if (cur_elm.first->left)
                q_isRight.push({ cur_elm.first->left, false });
            if (cur_elm.first->right)
                q_isRight.push({ cur_elm.first->right, true });
        }
        else {
            level_order.push_back(cur_level_order);
            cur_level_order.clear();
            if (!q_isRight.empty()) {
                q_isRight.push({ nullptr, false });
            }
        }
    }

    if (level_order.size() == 1)
        return { level_order[0][0].first };

    // calculate anti-clock-wise order size
    int total_size = 0;
    total_size += level_order.front().size();
    for (int i = 1; i < level_order.size() - 1; i++) {
        total_size += min(int(level_order.at(i).size()), 2);
    }
    total_size += level_order.back().size();

    // fill in the details
    vector<int> anti_clockwise_order(total_size);
    int iter_front = 0;
    int iter_back = total_size - 1;
    anti_clockwise_order[iter_front++] = level_order.front()[0].first;
    for (int i = 1; i < level_order.size() - 1; i++) {
        if (level_order[i].size() == 1) {
            bool isRight = level_order[i][0].second;
            if (isRight)
                anti_clockwise_order[iter_back--] = level_order[i].front().first;
            else anti_clockwise_order[iter_front++] = level_order[i].front().first;
        }
        else {
            anti_clockwise_order[iter_front++] = level_order[i].front().first;
            anti_clockwise_order[iter_back--] = level_order[i].back().first;
        }
    }
    for (int i = 0; i < level_order.back().size(); i++) {
        anti_clockwise_order[iter_front++] = level_order.back()[i].first;
    }

    return anti_clockwise_order;
}

Last updated