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)
  • 相关阅读:
    scrapy 第一个案例(爬取腾讯招聘职位信息)
    scrapy 代码调试用 shell
    scrapy 命令行创建 启动 跟踪
    scrapy 手动编写模板
    scrapy安装
    爬虫之xpath用法
    爬虫之 beautifusoup4
    抓包工具fiddler
    12306登录爬虫 session版本
    Drainage Ditches(dinic)
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523911.html
Copyright © 2011-2022 走看看