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
.node
Initially, all next pointers are set to NULL
.python
Note:spa
For example, Given the following perfect binary tree,指针
1 / \ 2 3 / \ / \ 4 5 6 7
After calling your function, the tree should look like:code
1 -> NULL / \ 2 -> 3 -> NULL / \ / \ 4->5->6->7 -> NULL
# Definition for a binary tree node # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None # self.next = None
class Solution: # @param root, a tree node # @return nothing def connect(self, root): if not root: return None last = root cur = root while last.left: # 保证其不是叶节点 cur = last while cur: cur.left.next = cur.right if cur.next: # 当前节点右节点的下一个指向当前节点下一个的左节点 cur.right.next = cur.next.left cur = cur.next last = last.left return None