LeetCode 116. Populating Next Right Pointers in Each Node

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

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.

so in general, you should do something to make it:
在这里插入图片描述
just thinking straight, use two pointers, one pointer controls the head of each level, named it start.
and another one will go through each level, it’s a sub pointer which will be initialize at that start pointer.

class Solution {
    public Node connect(Node root) {
        Node start = root;
        
        while (start != null) {
            Node cur = start;
            while (cur != null) {
                if (cur.left != null) {
                    cur.left.next = cur.right;
                }
                if (cur.right != null && cur.next != null) {
                    cur.right.next = cur.next.left;
                }
                cur = cur.next;
            }
            start = start.left;
        }
        return root;
    }
}
posted @ 2020-11-19 03:28  EvanMeetTheWorld  阅读(16)  评论(0)    收藏  举报