zoukankan      html  css  js  c++  java
  • 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

     Populating Next Right Pointers in Each Node系列的第一题。这一题要求较松,树是完全二叉树,不用担心存在左子树或是右子树缺失的情况。题目要求使用constant space.所以递归的深搜解法其实是不行。这题的处理顺序符合层搜要求。一般层搜也需要使用queue来实现一层与下一层之间的交互。但是如果使用queue的话空间复杂度为O(logn),也不符合题目要求。让我们考虑下,在建立某层的右向连接时,其上一层的右向连接已经建立,成为一个linkedlist。利用这个linkedlist,一个结点一个结点去处理,空间复杂度就降到了O(1)。所以这题的思路是利用当前层已建立的连接,去处理下一层的连接。头结点只有一个,可以认为已经建立好了连接,从头结点这层开始向下处理。时间复杂度O(n),空间复杂度O(1),代码如下:

    class Solution(object):
        def connect(self, root):
            """
            :type root: TreeLinkNode
            :rtype: nothing
            """
            if not root:
                return
            prev = root 
            while(prev.left):
                cur = prev
                while cur:
                    if cur.left:
                        cur.left.next = cur.right   #结点内的连接
                    if cur.next:
                        cur.right.next = cur.next.left #跨上一层的结点
                    cur = cur.next
                prev = prev.left

    prev为上一层的开始结点,cur为上一层正在处理的结点,因为是完全二叉树,完全可以从上一层的结点建立下一层结点之间的联系。完全二叉树的设置使这题非常简单。Populating Next Right Pointers in Each Node II 这道题要求处理不是完全二叉树的情况,就没那么简单了。

  • 相关阅读:
    谈软件开发工具的选择
    Windows下搭建Octopress博客
    Aspose Word模版使用总结篇2带示例
    强大的二分查找法(Binary Search)
    GhostDoc Pro v4.5.13017专业破解版本
    超炫的开源 JavaScript 物理引擎
    CQRS + DDD + MDP 实现快速应用程序开发
    数据结构之栈(Stack)与队列(Queue)
    插件框架实现
    集成服务监控器green.monitor发布
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5482680.html
Copyright © 2011-2022 走看看