117 Populating Next Right Pointers in Each Node II *****imp & representative

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 toNULL.

Initially, all next pointers are set toNULL.

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

注意一下 注意一下这个结构

要用一个levelhead告诉你每次curt 变到下一排

要用一个prev永远标记上一个

要用一个curt标记当前到哪里了

      1
    2   3
  4 .     5
/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
/***
             {0,2,4,1,#,3,-1,5,1,#,6,#,8}
                   0  
                2      4
             1      3     -1
           5   1      6       8

***/

public class Solution {
    public void connect(TreeLinkNode root) {
        if (root == null) {
            return;
        }
        TreeLinkNode pre = null;
        TreeLinkNode levelHead = null;
        TreeLinkNode curt = root;

        while (curt != null) {

            while (curt != null) {
                if (curt.left != null) {
                    if (pre == null) {
                        pre = curt.left;
                        levelHead = curt.left;
                    } else {
                        pre.next = curt.left;
                        pre = pre.next;
                    } 
                 }
                if (curt.right != null) {
                    if (pre == null) {
                        pre = curt.right;
                        levelHead = curt.right;
                    }else {
                        pre.next = curt.right;
                        pre = pre.next;
                    }
                }
                curt = curt.next;
            }
            curt = levelHead;
            levelHead = null;
            pre = null;
        }


    }
}

results matching ""

    No results matching ""