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)
  • 相关阅读:
    文件与流之动手动脑
    四则运算1.1版
    2018年11月16日编程体会
    JAVA(1)之关于对象数组作形参名的方法的使用
    re模块 时间模块
    日志模块
    软件开发目录规范
    模块和包
    内置函数
    匿名函数
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523911.html
Copyright © 2011-2022 走看看