首页 > 其他 > 详细

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

时间:2020-10-28 15:33:27      阅读:44      评论:0      收藏:0      [点我收藏+]

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;
    }
};

 

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

原文:https://www.cnblogs.com/xuningwang/p/13891016.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!