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)
  • 相关阅读:
    static心得
    建库注意
    Django之模板层
    Django之视图层
    Django之路由层
    Django开篇
    HTTP协议——详细版
    前端之bootstrap
    前端之Jquery
    前端之BOM和DOM
  • 原文地址:https://www.cnblogs.com/loadofleaf/p/5523911.html
Copyright © 2011-2022 走看看