Contents

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


117. Populating Next Right Pointers in Each Node II


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,null,7] Output: [1,#,2,3,#,4,5,7,#] Explanation: Given the above 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: []


解題思路 :

  • 這題可以直接參考 leetcode116題解,他們的解法一模一樣
  • 差別就只有在leetcode117不一定是prefect binary tree,但對於我使用的解法是通用的! trace一下code馬上就能發現端倪!

Queue解法

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

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


 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
/**
 * 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” 我們峰頂見!!!