📑 题目:116. 填充每个节点的下一个右侧节点指针

🚀 本题 LeetCode 传送门

题目大意

给定一个 完美二叉树 ,其所有叶子节点都在同一层,每个父节点都有两个子节点。二叉树定义如下:

React JSX

  1. struct Node {
  2. int val;
  3. Node *left;
  4. Node *right;
  5. Node *next;
  6. }

填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。初始状态下,所有 next 指针都被设置为 NULL。

解题思路

  • 本质上是二叉树的层序遍历,基于广度优先搜索,将每层的节点放入队列,并遍历队列进行连接。

代码

  1. package leetcode
  2. type Node struct {
  3. Val int
  4. Left *Node
  5. Right *Node
  6. Next *Node
  7. }
  8. //解法一:迭代
  9. func connect(root *Node) *Node {
  10. if root == nil {
  11. return root
  12. }
  13. q := []*Node{root}
  14. for len(q) > 0 {
  15. var p []*Node
  16. // 遍历这一层的所有节点
  17. for i, node := range q {
  18. if i+1 < len(q) {
  19. node.Next = q[i+1]
  20. }
  21. if node.Left != nil {
  22. p = append(p, node.Left)
  23. }
  24. if node.Right != nil {
  25. p = append(p, node.Right)
  26. }
  27. }
  28. q = p
  29. }
  30. return root
  31. }
  32. // 解法二 递归
  33. func connect2(root *Node) *Node {
  34. if root == nil {
  35. return nil
  36. }
  37. connectTwoNode(root.Left, root.Right)
  38. return root
  39. }
  40. func connectTwoNode(node1, node2 *Node) {
  41. if node1 == nil || node2 == nil {
  42. return
  43. }
  44. node1.Next = node2
  45. connectTwoNode(node1.Left, node1.Right)
  46. connectTwoNode(node2.Left, node2.Right)
  47. connectTwoNode(node1.Right, node2.Left)
  48. }