116. Populating Next Right Pointers in Each Node

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了116. Populating Next Right Pointers in Each Node相关的知识,希望对你有一定的参考价值。

?????????binary   set   ?????????   child   evel   pre   src   color   init   

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.

 

Example:

????????????

 

??????????????????????????????????????? https://segmentfault.com/a/1190000003465911

1. ???????????????

??????

?????????????????????next???????????????????????????????????????????????????????????????????????????????????????????????????????????????next????????????????????????????????????????????????????????????i??????next????????????????????????next???????????????????????????????????????

// Definition for a Node.
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val,Node _left,Node _right,Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
*/
class Solution {
    public Node connect(Node root) {
                Node level_start=root;
        while(level_start!=null){
            Node cur=level_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;
            }
            level_start=level_start.left;
        }
        return root;
    }
}

 

以上是关于116. Populating Next Right Pointers in Each Node的主要内容,如果未能解决你的问题,请参考以下文章

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

116. Populating Next Right Pointers in Each Node

LeetCode 116 Populating Next Right Pointers in Each Node