Leetcode - Binary Tree Right Side View
Leetcode - Populating Next Right Pointers in Each Node II

Leetcode - Populating Next Right Pointers in Each Node

violet posted @ Apr 25, 2020 06:25:14 AM in 算法 with tags Algorithm Golang tree , 166 阅读

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.

 

Follow up:

  • You may only use constant extra space.
  • Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

 

Example 1:

 

/**
 * Definition for a Node.
 * type Node struct {
 *     Val int
 *     Left *Node
 *     Right *Node
 *     Next *Node
 * }
 */

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

登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter