117. Populating Next Right Pointers in Each Node II

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

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

一刷
題解:
創建3個節點,cur(處于當前層), prev(處于操作層), head(下一層的最外節點)。即 cur-1, prev-2, head-3

/**
 * Definition for binary tree with next pointer.
 * public class TreeLinkNode {
 *     int val;
 *     TreeLinkNode left, right, next;
 *     TreeLinkNode(int x) { val = x; }
 * }
 */
public class Solution {
    public void connect(TreeLinkNode root) {
        TreeLinkNode head = null;//the head of the next level
        TreeLinkNode prev = null;// the leading node of next level
        TreeLinkNode cur = root; //current node of current level
        
        //cur-1, prev-2, head-3
        
        while(cur!=null){
            while(cur!=null){
                //current manipulate-level 2
                if(cur.left!=null){
                    if(prev == null){
                        head = cur.left;
                    }
                    else prev.next = cur.left;
                    prev = cur.left;
                }
                
                if(cur.right!=null){
                    if(prev == null) head = cur.right;
                    else prev.next = cur.right;
                    prev = cur.right;
                }
                cur = cur.next;
            }
            cur = head;
            head = null;
            prev = null;
        }
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容