1. 程式人生 > >【LeetCode】82. Populating Next Right Pointers in Each Node

【LeetCode】82. Populating Next Right Pointers in Each Node

題目描述(Hard)

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.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

題目連結

Example 1:

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

演算法分析

提交程式碼:

class Solution {
public:
    void connect(TreeLinkNode *root) {
        connect(root, NULL);
    }
    
    void connect(TreeLinkNode *root, TreeLinkNode *brother) {
        if (!root) return;
        root->next = brother;
        
        connect(root->left, root->right);
        
        if (brother)
            connect(root->right, brother->left);
        else
            connect(root->right, NULL);
    }
};

提交程式碼:

class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (!root) return;
        while(root)
        {
            // 下一層的首節點
            TreeLinkNode *next = NULL;
            // 前驅
            TreeLinkNode *prev = NULL;
        
            for (; root; root = root->next)
            {
                if (!next) next = root->left ? root->left : root->right;
                
                if (root->left)
                {
                    if (prev) prev->next = root->left;
                    prev = root->left;
                }
                
                if (root->right)
                {
                    if (prev) prev->next = root->right;
                    prev = root->right;
                }
            }
            
            root = next;
        }
    }
};