[Leetcode]Populating Next Right Pointers in Each Node II

来源:互联网 发布:java中的迭代器 编辑:程序博客网 时间:2024/05/21 06:57

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,
Given the following binary tree,

         1       /  \      2    3     / \    \    4   5    7

After calling your function, the tree should look like:

         1 -> NULL       /  \      2 -> 3 -> NULL     / \    \    4-> 5 -> 7 -> NULL

Populating Next Right Pointers in Each Node的扩展题~还是要求用常数空间,不过树不是完全二叉树~下面解法其实思路挺简单的,明白了的话写起来也会很顺手~

class Solution:    # @param root, a tree node    # @return nothing    def connect(self, root):        cur, head, prev = root, None, None        while cur:            while cur:                if cur.left:                    if prev:                        prev.next = cur.left                    else:                        head = cur.left                    prev = cur.left                if cur.right:                    if prev:                        prev.next = cur.right                    else:                        head = cur.right                    prev = cur.right                cur = cur.next            cur = head            prev, head = None, None


0 0
原创粉丝点击