Leetcode 116. Populating Next Right Pointers in Each Node

Leetcode 116. Populating Next Right Pointers in Each Node

@(LeetCode)[LeetCode | Algorithm]

Given a binary tree, 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.

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

For example, given the following perfect binary tree,

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

After calling your function, the tree should look like:

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

Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).


Solution #1 Queue + BFS

Time: O(n)
Space: O(n)

Space complexity is O(n) in this solution, which does NOT satisfy the requirement…

The key idea is that we can utilize a queue to implement BFS and setup the next pointer. And the next pointer should point to NULL every 2k1 where (k=1,2,3...) .

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if(!root)
            return;
        int cnt = 0;
        int next_null = 2;
        queue<TreeLinkNode *> q;
        q.push(root);

        while( !q.empty() ){
            TreeLinkNode *node = q.front();
            q.pop();

            if(node->left)
                q.push(node->left);
            if(node->right)
                q.push(node->right);

            if(++cnt == next_null - 1) {
                next_null *= 2;
                node->next = NULL;
            }
            else {
                node->next = q.front();
            }
        }
    }
};

Solution 2: Constant Space Solution

Time: O(n)
Space: O(1)

The key idea is that: at current layer, we can build the next pointer for the next layer.

sample

As show in the figure above, there two kinds of next pointers:
1. next pointer between two nodes who share same parent (the green one)
2. next pointer between two nodes who have different parents (the red one)

核心思想就是:在当前层完成下一层的next指针的构建。

如上图所示,有两种next指针需要构建:一种是同一父节点下的两个children之间的next;另一种情况是两个节点的父节点相邻。图中已经给出了如何处理这两种情况的伪代码。

class Solution {
public:
    void connect(TreeLinkNode *root) {        
        TreeLinkNode *left_most = root;

        while(left_most) {
            TreeLinkNode *node = left_most;

            // go through each layer
            while(node && node->left) {
                node->left->next = node->right;
                node->right->next = node->next ? node->next->left : NULL;
                // move to the next node
                node = node->next;
            }

            // move to next layer
            left_most = left_most->left;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/zzy_zhangzeyu_/article/details/79692871