117. Populating Next Right Pointers in Each Node II

问题描述:

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

解题思路:

这道题要求我们用O(1)的空间复杂度,那么很显然,队列是不能再用的。

那我们可以用指针来遍历。

这里很巧妙的一点是:在我当前的节点我去连接前一个节点和现在的节点,因为我也不知道下一个离当前节点最近的节点是哪一个节点。

而判断该节点是否为这一层的头节点也十分巧妙:看前一个节点是不是不存在

代码:

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        TreeLinkNode* head = NULL;
        TreeLinkNode* prev = NULL;
        TreeLinkNode* cur = root;
        
        while(cur){
            while(cur){
                if(cur->left){
                    if(prev) prev->next = cur->left;
                    else head = cur->left;
                    prev = cur->left;
                }
                if(cur->right){
                    if(prev) prev->next = cur->right;
                    else head = cur->right;
                    prev = cur->right;
                }
                cur = cur->next;
            }
            cur = head;
            head = NULL;
            prev = NULL;
        }
    }
};
原文地址:https://www.cnblogs.com/yaoyudadudu/p/9348943.html