本题其实想通了,就是一道中等难度的Medium,但是如果想不通,就是Hard。。
    换句话说,难度在于思路,而不是实现

    本题如果没有117. Populating Next Right Pointers in Each Node II - 图1空间的要求,就可以用BFS解决,但是因为加了这个要求,就给了人一种无法用BFS解决的错觉,而想办法用DFS解决。应该说或许DFS也能解决,但是BFS解决起来真的不难。

    • 尝试连接每一层的所有Node
    • 假设上次层的连接好了,就可以运用上一层的Node + 一个for loop连接下一层的所有node
    • 需要一个virtualNode帮我们做到这些 117. Populating Next Right Pointers in Each Node II - 图2
    • 时间复杂度:117. Populating Next Right Pointers in Each Node II - 图3
    • 空间复杂度: 117. Populating Next Right Pointers in Each Node II - 图4

    如上图所示,如果2,3相连,并有一个virtualNode指向4,则很容易将4,5,7相连,代码如下:

    1. /*
    2. // Definition for a Node.
    3. class Node {
    4. public int val;
    5. public Node left;
    6. public Node right;
    7. public Node next;
    8. public Node() {}
    9. public Node(int _val) {
    10. val = _val;
    11. }
    12. public Node(int _val, Node _left, Node _right, Node _next) {
    13. val = _val;
    14. left = _left;
    15. right = _right;
    16. next = _next;
    17. }
    18. };
    19. */
    20. class Solution {
    21. public Node connect(Node root) {
    22. Node head = root;
    23. while (head != null) {
    24. Node virtualHead = new Node(-1);
    25. Node current = virtualHead;
    26. for (Node tmp = head; tmp != null; tmp = tmp.next) {
    27. if (tmp.left != null) {
    28. current.next = tmp.left;
    29. current = current.next;
    30. }
    31. if (tmp.right != null) {
    32. current.next = tmp.right;
    33. current = current.next;
    34. }
    35. }
    36. head = virtualHead.next;
    37. }
    38. return root;
    39. }
    40. }