leetcode117 - Populating Next Right Pointers in Each Node II - medium

Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

 

Follow up:

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

 

Example 1:

Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

 

Constraints:

  • The number of nodes in the given tree is less than 6000.
  • -100 <= node.val <= 100
 
比较116需要注意的地方1. 下一层的first不再是当前first的left了,是第一个当前层的非空子node。2. left, right的next都不再固定了,如果同时有left,right,那left还是指向right,其余情况next都是当前node后续同层node的第一个非空子node。用两个helper func即可。
 
实现:Time O(n) Space O(1)
class Solution {
private:
    Node* findNextForChild(Node* node){
        node = node->next;
        while (node){
            if (node->left)
                return node->left;
            if (node->right)
                return node->right;
            node = node->next;
        }
        return node;
    }
    
    Node* findNextLevelFirst(Node* node){
        while (node){
            if (node->left)
                return node->left;
            if (node->right)
                return node->right;
            node = node->next;
        }
        return node;
    }
    
public:
    Node* connect(Node* root) {
        if (!root) return nullptr;
        Node* first = root;
        while (first){
            Node* cur = first;
            while (cur){
                if (cur->left){
                    if (cur->right) cur->left->next = cur->right;
                    else{
                        Node* nxt = findNextForChild(cur);
                        cur->left->next = nxt;
                    }
                }
                if (cur->right){
                    Node* nxt = findNextForChild(cur);
                    cur->right->next = nxt;
                }
                cur = cur->next;
            }
            first = findNextLevelFirst(first);
        }
        return root;
    }
};

 

posted @ 2020-10-28 14:40  little_veggie  阅读(100)  评论(0)    收藏  举报