[LeetCode系列]Populating Next Right Pointers in Each Node II

将会陆续放出本人刷LeetCode所见到的一些比较有趣或者不会的题目的随笔。

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1
       /  
      2    3
     /     
    4   5    7

After calling your function, the tree should look like:

         1 -> NULL
       /  
      2 -> 3 -> NULL
     /     
    4-> 5 -> 7 -> NULL

此题有

Populating Next Right Pointers in Each Node I

两题有一些有趣的区别,第二题是非完全二叉树。所以在做第一题时用了队列对每一层的每个节点进行连接,但在这一题里面就无法简单地通过这个方法去实现。

一开始我同样用队列分层去实现,第i层的满节点数是Ki=2^(depth-1),实际节点数为Si,但因为是非完全二叉树,所以通过计算Ki-1-Si-1,那么第i层的节点数应该是Ki-(Ki-1-Si-1)-T, T为i-1层非空节点中left chile 或者 right child为空的个数。但用这个方法最后大数无法通过,暂时还没找出BUG。望哪位大神可以提供一个详细的队列方法的解题思路。

接下去是递归方法。

考虑的Point在每个节点的next节点可以在横向上找到存在的那个节点,无论是父节点next节点的左或者右孩子,又或者是父节点next的next节点的左或者右节点。

注意需要优先找出right child的next节点。

 1 /**
 2  * Definition for binary tree with next pointer.
 3  * public class TreeLinkNode {
 4  *     int val;
 5  *     TreeLinkNode left, right, next;
 6  *     TreeLinkNode(int x) { val = x; }
 7  * }
 8  */
 9 public class Solution {
10     public void connect(TreeLinkNode root) {
11       if (root == null) return;
12       TreeLinkNode p = root.next;
13       while (p != null) {
14           if (p.left != null) {
15               p = p.left;
16               break;
17           } else if (p.right != null) {
18               p = p.right;
19               break;
20           }
21           p = p.next;
22       }
23       
24       if (root.right != null) {
25           root.right.next = p;
26       } 
27       
28       if (root.left != null) {
29           root.left.next = root.right == null?p:root.right;
30       }
31       
32       connect(root.right);
33       connect(root.left);
34     }
35 
36 }
原文地址:https://www.cnblogs.com/Jam01/p/3633203.html