LEETCODE —— Populating Next Right Pointers in Each Node

Populating Next Right Pointers in Each Node

Given a binary treenode

    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }

 

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.算法

Initially, all next pointers are set to NULL.數據庫

Note:數據結構

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

 

For example,
Given the following perfect binary tree,app

         1
       /  \
      2    3
     / \  / \
    4  5  6  7

 

After calling your function, the tree should look like:spa

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

 

'''
Created on Nov 19, 2014

@author: ScottGu<gu.kai.66@gmail.com, 150316990@qq.com>
'''
# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#         self.next = None

class Solution:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        stack=[]
        if(root==None): return
        stack.append(root)
        while(len(stack)!=0):
            for ix in range(len(stack)-1):
                stack[ix].next=stack[ix+1]
            stack[-1].next=None
            cntOfLastLevel=len(stack)
            for ix in range(cntOfLastLevel):
                if (stack[0].left!=None):stack.append(stack[0].left)
                if (stack[0].right!=None):stack.append(stack[0].right)
                stack.remove(stack[0])
        
class Solution2:
    # @param root, a tree node
    # @return nothing
    def connect(self, root):
        if(root==None): return
        head_high=cursor_high=root
        head_low = cursor_low=None
        
        while(cursor_high.left!=None):
            head_low = cursor_low=cursor_high.left
         
            cursor_low.next=cursor_high.right
            cursor_low=cursor_low.next
            while(cursor_high.next!=None):
                cursor_high=cursor_high.next
                cursor_low.next=cursor_high.left
                cursor_low=cursor_low.next
                cursor_low.next=cursor_high.right
                cursor_low=cursor_low.next
            cursor_low.next=None
              
            head_high=cursor_high=head_low
        

題目和代碼如上所述,這個題比較有意思的地方是,這個數據結構有點像數據庫索引的結構,上述代碼實現了兩種方法,兩種方法都是層級遍歷,時間複雜度都是O(N),但空間複雜度不同,實現難度也不同。code

1. 第一種更爲簡單,但使用了額外的空間用於存儲上一層節點,最大空間複雜度爲全部葉子節點的大小之和。因此相似這種算法若是用於創建DB索引的話,恐怕內存就要爆掉了,第二種方法則沒有問題blog

2. 第二種稍複雜,可是空間複雜度只有O(1),也就是無需任何額外內存。實現方法是使用兩個遊標和1個標誌位,兩個遊標用於並行遍歷兩行nodes,1個標誌位用於標記下面那行的head。索引

 兩遊標並行往前走,會同時走到各自行的結尾,這時兩遊標各自下移到下一行開始(這就是爲啥要標記那行的head)而後重複上面的過程繼續往前走,當沒有下一行時中止(第二個遊標沒得指了),請自行腦補2個遊標遍歷全部nodes而且加連接的過程。內存

相關文章
相關標籤/搜索