题意:

image.png

解题思路:

  1. 思路:
  2. 1 -> NULL
  3. / \
  4. 2 -> 3 -> NULL
  5. / \ / \
  6. 4->5->6->7 -> NULL
  7. 1. 从根节点出发,每次遍历一层,遍历从左到右的顺序执行,对应每个节点,先让左儿子指向右儿子,然后让右儿子指向下一个节点的左儿子。最后让这一层最右侧的节点指向NULL
  8. 2. 遍历到叶节点所在的层为止;
  9. 模拟过程:
  10. * 第一步,遍历根节点,我们让根节点的左儿子指向右儿子,即让2指向3
  11. * 第二步,从左到右遍历第二层,先遍历2,让2的左儿子指向右儿子,即让4指向5,再让2的右儿子指向下一个节点的左儿子,即5指向6;然后遍历3,依次类推;
  12. * 第三步,我们发现第三层已经是叶节点,算法终止;
  13. 时间复杂度分析:每个节点仅会遍历一次,遍历时修改指针的时间复杂度是 O(1),所以总时间复杂度是 O(n)。

PHP代码实现:

  1. /**
  2. * Definition for a Node.
  3. * class Node {
  4. * function __construct($val = 0) {
  5. * $this->val = $val;
  6. * $this->left = null;
  7. * $this->right = null;
  8. * $this->next = null;
  9. * }
  10. * }
  11. */
  12. class Solution {
  13. /**
  14. * @param Node $root
  15. * @return Node
  16. */
  17. public function connect($root) {
  18. return $this->connectInteration($root);
  19. if ($root == null) return null;
  20. if ($root->left != null) {
  21. $root->left->next = $root->right;
  22. if ($root->next != null) {
  23. $root->right->next = $root->next->left;
  24. }
  25. }
  26. $this->connect($root->left);
  27. $this->connect($root->right);
  28. return $root;
  29. }
  30. function connectInteration($root) {
  31. $pre = $root;
  32. while ($pre != null) {
  33. $cur = $pre;
  34. while ($cur != null) {
  35. if ($cur->left != null) $cur->left->next = $cur->right;
  36. if ($cur->right != null && $cur->next != null) $cur->right->next = $cur->next->left;
  37. $cur = $cur->next;//同层移动
  38. }
  39. $pre = $pre->left; //移到下层
  40. }
  41. return $root;
  42. }
  43. }

GO代码实现:

  1. /**
  2. * Definition for a Node.
  3. * type Node struct {
  4. * Val int
  5. * Left *Node
  6. * Right *Node
  7. * Next *Node
  8. * }
  9. */
  10. func connect(root *Node) *Node {
  11. if root == nil {
  12. return nil
  13. }
  14. if root.Left == nil && root.Right == nil {
  15. return root
  16. }
  17. if root.Left != nil {
  18. root.Left.Next = root.Right
  19. }
  20. if root.Right != nil && root.Next != nil {
  21. root.Right.Next = root.Next.Left
  22. }
  23. connect(root.Left)
  24. connect(root.Right)
  25. return root
  26. }
  27. func connectInteration(root *Node) *Node {
  28. if root == nil {
  29. return nil
  30. }
  31. pre := root
  32. for pre.Left != nil {
  33. cur := pre
  34. for cur != nil {
  35. cur.Left.Next = cur.Right //左节点连接右节点
  36. if cur.Next != nil {
  37. cur.Right.Next = cur.Next.Left //右节点 连接 邻居左节点
  38. }
  39. cur = cur.Next //同层移动
  40. }
  41. pre = pre.Left //移到下层
  42. }
  43. return root
  44. }