Contents

[Golang][Leetcode][BinaryTree]刷題系列-116-Populating Next Right Pointers in Each Node


116. Populating Next Right Pointers in Each Node


Level : Medium

原題連結 : Click

題目 :

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 :

Note

Example 1:

Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#]

Explanation: Given the above perfect 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.

Example 2:

Input: root = [] Output: []


解題思路 :

  • 這題是level order traversal的變化題,一樣可以用queue來解決,可以參考 leetcode102題解
  • 將同一個level的node取出來時幫每一個node的Next設為下一個取出來的node,並將每一個level最後一個node的Next設為nil

Queue解法

  • time complexity: O(n) , space complexity: O(n)

Runtime: 4 ms, faster than 94.12% of Go online submissions for Populating Next Right Pointers in Each Node.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Left *Node
 *     Right *Node
 *     Next *Node
 * }
 */

func connect(root *Node) *Node {

    
    if root == nil {
        return root
    }
    
    var queue []*Node
    
    queue = append(queue,root)
    
    
    for len(queue) != 0 {
        
        length := len(queue)
        
        for i := 0; i < length; i++ {
            
            node := queue[0] 
            
            if i == length - 1 {
                node.Next = nil
            }else {
                node.Next = queue[1]
            }
            
            
            if node.Left != nil {
                queue = append(queue, node.Left)
            }
            
            if node.Right != nil {
                queue = append(queue, node.Right)
            }
            
            queue = queue[1:]
        }
        
    }
    
    return root	
}

最後祝福努力認真的各位 “All your dream of are hidden in your daily life” 我們峰頂見!!!