利用python 完成leetcode 117 填充每个节点的下一个右侧节点指针 II

给定一个二叉树

struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。

初始状态下,所有 next 指针都被设置为 NULL。

示例:

利用python 完成leetcode 117 填充每个节点的下一个右侧节点指针 II

输入:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","left":{"id”:“2”,“left”:{“KaTeX parse error: Expected 'EOF', got '}' at position 53: …t":null,"val":4}̲,"next":null,"r…id”:“4”,“left”:null,“next”:null,“right”:null,“val”:5},“val”:2},“next”:null,“right”:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …null,"right":{"id”:“6”,“left”:null,“next”:null,“right”:null,“val”:7},“val”:3},“val”:1}

输出:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …":"1","left":{"id”:“2”,“left”:{“KaTeX parse error: Expected '}', got 'EOF' at end of input: …:null,"next":{"id”:“4”,“left”:null,“next”:{“KaTeX parse error: Expected 'EOF', got '}' at position 53: …t":null,"val":7}̲,"right":null,"…id”:“6”,“left”:null,“next”:null,“right”:{“KaTeX parse error: Expected 'EOF', got '}' at position 9: ref":"5"}̲,"val":3},"righ…ref”:“4”},“val”:2},“next”:null,“right”:{"$ref":“6”},“val”:1}

解释:给定二叉树如图 A 所示,你的函数应该填充它的每个 next 指针,以指向其下一个右侧节点,如图 B 所示。

提示:

你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
思路
一层一层遍历,因为有next所以会方便很多
首先建立一个节点M,使M节点的next始终指向当前行最左子节点,(如示例,遍历第2,3所在一行时,M.next=4)然后通过next遍历当前行,将每个子节点用next相连,当前行遍历完毕时,通过M.next到达下一行的最左节点,同时将M.next置为None,否则如果这一行的节点都没有子节点的话,会一直循环下去,(当前行遍历完毕时M没有任何修改,又回到最左侧节点)
代码

def connect(self, root: 'Node') -> 'Node':
        head=root
        M=Node(0,None,None,None)
        N=M
        while(root!=None):
            if root.left!=None:
                N.next=root.left
                N=N.next
            if root.right!=None:
                N.next=root.right
                N=N.next
            root=root.next
            if root==None:
                root=M.next
                N=M
                N.next=None
        return head