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

image.png

0. 鏈接

題目鏈接

1. 題目

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

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,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect 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 4096.
-1000 <= node.val <= 1000

2. 思路1: 隊列+分層迭代

  • 時間復(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.left = Node(6)
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-6-7=>null
6-null-null=>null
7-null-null=>null
==================================================
1-2-3=>null
2-4-5=>3
4-null-null=>5
5-null-null=>6
3-6-7=>null
6-null-null=>7
7-null-null=>null

4. 結(jié)果

image.png

5. 思路2: 遞歸

  • 時間復(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':
        if root is None:
            return
        if root.left is not None:
            root.left.next = root.right
            if root.next is not None:
                root.right.next = root.next.left
        self.connect(root.left)
        self.connect(root.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 = 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.left = Node(6)
node.right.right = Node(7)
print_tree(root1)
print('=' * 50)
solution.connect(root1)
print_tree(root1)

7. 結(jié)果

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

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