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)
  • 相关阅读:
    python3.5中的格式化输出
    关于IDE集成开发环境,Pycharm小技巧
    python3.5中的赋值运算符和逻辑运算符
    SecureCRT 使用技巧
    selenium-键盘和鼠标事件
    selenium-各种定位方法
    selenium-百度搜索框输入后,定位联想下拉框元素
    selenium
    mysql-client 与mysql-server的区别
    MySql8.0.15 window 初始化 修改密码
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523911.html
Copyright © 2011-2022 走看看