题意:

image.png

解题思路:

  1. 思路:
  2. 对每个节点:
  3. 1. 左子右子都有,则左子next指向右子,右子next指向findNextChild
  4. 2. 只有左子,左子指向findNextChild
  5. 3. 只有右子,右子指向findNextChild
  6. 注意:递归时要先递归右子树,否则上级节点next关系没建好,下级无法成功findNextChild

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. if ($root == null) return null;
  19. if ($root->left != null) {
  20. $root->left->next = ($root->right != null) ? $root->right : $this->findNextChild($root);
  21. }
  22. if ($root->right != null) {
  23. $root->right->next = $this->findNextChild($root);
  24. }
  25. $this->connect($root->right);
  26. $this->connect($root->left);
  27. return $root;
  28. }
  29. function findNextChild($root) {
  30. if ($root->next == null) return null;
  31. while ($root->next != null) {
  32. if ($root->next->left != null) return $root->next->left;
  33. if ($root->next->right != null) return $root->next->right;
  34. $root = $root->next;
  35. }
  36. return null;
  37. }
  38. }

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.Right.Next = next(root.Next)
  19. } else {
  20. root.Left.Next = root.Right
  21. }
  22. if root.Right == nil {
  23. root.Left.Next = next(root.Next)
  24. } else {
  25. root.Right.Next = next(root.Next)
  26. }
  27. // 需要先递归右子树
  28. connect(root.Right)
  29. connect(root.Left)
  30. return root
  31. }
  32. func next(root *Node) *Node {
  33. if root == nil {
  34. return nil
  35. }
  36. for ;root != nil; root = root.Next {
  37. if root.Left != nil {
  38. return root.Left
  39. }
  40. if root.Right != nil {
  41. return root.Right
  42. }
  43. }
  44. return nil
  45. }