算法题--连接二叉树同层节点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: 队列+分层迭代

  • 时间复杂度: O(N)
  • 空间复杂度: 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)



输出结果

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. 结果

image.png

5. 思路2: 三个指针+分层迭代

  • 时间复杂度: O(N)
  • 空间复杂度: 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)



输出结果

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. 结果

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容