您的位置:首页 > Web前端 > Node.js

LeetCode Populating Next Right Pointers in Each Node II

2016-03-16 14:24 363 查看

LeetCode解题之Populating Next Right Pointers in Each Node II

原题

为二叉树的节点都添加一个next指针,指向跟它在同一高度的右边的节点,如果右边没有节点,就指向None。与 Populating Next Right Pointers in Each Node 的区别就是这里的二叉树可以是不完全二叉树。

注意点:

最好只用常量的空间

例子:

输入:

[code]         1
       /  \
      2    3
     / \    \
    4   5    7


输出:

[code]         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \    \
    4-> 5 -> 7 -> NULL


解题思路

Populating Next Right Pointers in Each Node 中广度优先遍历的方法已经能够处理不是完全二叉树的情况,但没有做到常量空间,这里对代码进行一下优化。仔细想一下,既然上一层的节点已经通过next指针连起来了,那么就只要能得到上一层的第一个节点就可以依次把上一层节点的子节点串联起来了。通过添加一个假节点来标记当前行的首节点。其中root表示上一行遍历到的节点,node表示当前行的节点。

AC源码

[code]# 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
        """
        dummy = TreeLinkNode(-1)
        node = dummy
        while root:
            while root:
                node.next = root.left
                node = node.next or node
                node.next = root.right
                node = node.next or node
                root = root.next
            root, node = dummy.next, dummy

if __name__ == "__main__":
    None


欢迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 来获得相关源码。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: