Medium

Len Chen
1 min readOct 29, 2018

Problem

Given a binary tree

struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • Recursive approach is fine, implicit stack space does not count as extra space for this problem.

Example:

Given the following binary tree,

    1
/ \
2 3
/ \ \
4 5 7

After calling your function, the tree should look like:

    1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4 -> 5 -> 7 -> NULL

Solution

Iterate each level of nodes to concat every nodes together. This solution is more general so it can also be used in #116, but it’s slower because of condition checking.

Complexity

It’s obvious that we only traverse each node once, so its time complexity is O(n), where n denotes to counts of nodes in this tree. And it’s trivial that we only use O(1) extra space.

--

--

Len Chen
Len Chen

No responses yet