美文网首页算法学习
算法题--连接二叉树同层节点

算法题--连接二叉树同层节点

作者: 岁月如歌2020 | 来源:发表于2020-05-02 21:47 被阅读0次
    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: 队列+分层迭代

    • 时间复杂度: ```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.left = Node(6)
    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-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. 结果

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

    image.png

    相关文章

      网友评论

        本文标题:算法题--连接二叉树同层节点

        本文链接:https://www.haomeiwen.com/subject/zpvlghtx.html