算法題--連接二叉樹同層節(jié)點(diǎn)II

image.png

0. 鏈接

題目鏈接

1. 題目

Given a binary tree

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *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.

Follow up:

You may only use constant extra space.
Recursive approach is fine, you may assume implicit stack space does not count as extra space for this problem.

Example 1:


示意圖
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Given the above binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with '#' signifying the end of each level.

Constraints:

The number of nodes in the given tree is less than 6000.
-100 <= node.val <= 100

2. 思路1: 隊(duì)列+分層迭代

  • 時(shí)間復(fù)雜度: O(N)
  • 空間復(fù)雜度: O(N)

3. 代碼

# coding:utf8


# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    def connect(self, root: 'Node') -> 'Node':
        if root is None:
            return None

        queue = list()
        queue.append(root)
        while len(queue) > 0:
            size = len(queue)
            pre = None
            for i in range(size):
                each_node = queue.pop(0)
                if pre is not None:
                    pre.next = each_node
                pre = each_node
                if each_node.left is not None:
                    queue.append(each_node.left)
                if each_node.right is not None:
                    queue.append(each_node.right)

        return root


def print_tree(node):
    if node is None:
        return
    left = str(node.left.val) if node.left is not None else 'null'
    right = str(node.right.val) if node.right is not None else 'null'
    next = str(node.next.val) if node.next is not None else 'null'
    print('{}-{}-{}=>{}'.format(node.val, left, right, next))
    if node.left is not None:
        print_tree(node.left)
    if node.right is not None:
        print_tree(node.right)


solution = Solution1()

root1 = node = Node(1)
node.left = Node(2)
node.right = Node(3)
node.left.left = Node(4)
node.left.right = Node(5)
node.right.right = Node(7)
print_tree(root1)
print('=' * 50)
solution.connect(root1)
print_tree(root1)



輸出結(jié)果

1-2-3=>null
2-4-5=>null
4-null-null=>null
5-null-null=>null
3-null-7=>null
7-null-null=>null
==================================================
1-2-3=>null
2-4-5=>3
4-null-null=>5
5-null-null=>7
3-null-7=>null
7-null-null=>null

4. 結(jié)果

image.png

5. 思路2: 三個(gè)指針+分層迭代

  • 時(shí)間復(fù)雜度: O(N)
  • 空間復(fù)雜度: O(1)

6. 代碼

# coding:utf8


# Definition for a Node.
class Node:
    def __init__(self, val: int = 0, left: 'Node' = None, right: 'Node' = None, next: 'Node' = None):
        self.val = val
        self.left = left
        self.right = right
        self.next = next


class Solution:
    def connect(self, root: 'Node') -> 'Node':
        head = pre = None
        cur = root
        while cur is not None:
            while cur is not None:
                if cur.left is not None:
                    if pre is not None:
                        pre.next = cur.left
                    else:
                        head = cur.left
                    pre = cur.left

                if cur.right is not None:
                    if pre is not None:
                        pre.next = cur.right
                    else:
                        head = cur.right
                    pre = cur.right

                cur = cur.next

            cur = head
            pre = head = None
        return root


def print_tree(node):
    if node is None:
        return
    left = str(node.left.val) if node.left is not None else 'null'
    right = str(node.right.val) if node.right is not None else 'null'
    next = str(node.next.val) if node.next is not None else 'null'
    print('{}-{}-{}=>{}'.format(node.val, left, right, next))
    if node.left is not None:
        print_tree(node.left)
    if node.right is not None:
        print_tree(node.right)


solution = Solution()

root1 = node = Node(1)
node.left = Node(2)
node.right = Node(3)
node.left.left = Node(4)
node.left.right = Node(5)
node.right.right = Node(7)
print_tree(root1)
print('=' * 50)
solution.connect(root1)
print_tree(root1)



輸出結(jié)果

1-2-3=>null
2-4-5=>null
4-null-null=>null
5-null-null=>null
3-null-7=>null
7-null-null=>null
==================================================
1-2-3=>null
2-4-5=>3
4-null-null=>5
5-null-null=>7
3-null-7=>null
7-null-null=>null

7. 結(jié)果

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容