zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):116 Populating Next Right Pointers in Each Node

    题目来源


    https://leetcode.com/problems/populating-next-right-pointers-in-each-node/

    Given a binary tree

        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,

             1
           /  
          2    3
         /   / 
        4  5  6  7

    After calling your function, the tree should look like:

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

    题意分析


    Input:满二叉树

    Output:增加了next信息的满二叉树

    Conditions:只能使用常量空间


    题目思路


    注意到是满二叉树,并且上一层的next信息可以用于下一层。


    AC代码(Python)

    # Definition for binary tree with next pointer.
    # class TreeLinkNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    #         self.next = None
    
    class Solution(object):
        def connect(self, root):
            """
            :type root: TreeLinkNode
            :rtype: nothing
            """
            if root and root.left:
                root.left.next = root.right
                if root.next:
                    root.right.next = root.next.left
                else:
                    root.right.next = None
                self.connect(root.left)
                self.connect(root.right)
  • 相关阅读:
    AI---ListPicker的使用
    AI---Screen & Notifier
    Android---开发环境
    Android---App Inventor环境搭建
    OS---host文件
    JAVA---接口与抽象类
    JAVA---类成员的访问权限
    JSP---一个Servlet处理多个请求操作
    hdu 6016
    hdu 6019
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523911.html
Copyright © 2011-2022 走看看