java 117.在每个节点II.java中填充下一个右指针

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 117.在每个节点II.java中填充下一个右指针相关的知识,希望对你有一定的参考价值。

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
 
 /*
          1 -> NULL
       /    \
      2  ->  3 -> NULL
       \    / \
        4->5 ->7 -> NULL
        
        
             1
           /  \
          2    3
         / \    \
        4   5    7
       / \      / \
      8   9    10 11
        
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode frontier = root;
        
        while(frontier != null) {
            TreeLinkNode cur = frontier; //current node of current level
            TreeLinkNode head = null; //head of the next level
            TreeLinkNode prev = null; //the leading node on the next level
            while(cur != null) {
                if(cur.left != null) {
                    if(prev != null) {
                        prev.next = cur.left;
                    } else {
                        head = cur.left;
                    }
                    prev = cur.left;
                }
                
                if(cur.right != null) {
                    
                    if (prev != null) {
                        prev.next = cur.right;
                    } else {
                        head = cur.right;
                    }
                    prev = cur.right;
                }
                cur = cur.next;
            }
            frontier = head;
        }
    }
}

以上是关于java 117.在每个节点II.java中填充下一个右指针的主要内容,如果未能解决你的问题,请参考以下文章

java 117.在每个节点II.java中填充下一个右指针

java 117.在每个节点II.java中填充下一个右指针

java 117.在每个节点II.java中填充下一个右指针

java 117.在每个节点II.java中填充下一个右指针

c_cpp 117.在每个节点中填充下一个右指针II - DifficultyMedium - 2018.9.12

Leetcode 117. 填充每个节点的下一个右侧节点指针 II