描述
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
分析
可以用广度优先遍历,用队列实现。其中用了Zigzag Level Traversal中的一个技巧,在队列里加入None来分隔各个level。
但这样空间复杂度是O(n)的,题目里要求O(1)。由于我们的节点多了一个指针,其实可以用这个指针来完成广度优先遍历,不再需要队列。方法是用一层一层遍历,当前层时把下一层节点的next指针设置好。
代码
广度优先遍历, 空间O(n)
1 | # Definition for binary tree with next pointer. |
空间O(1)算法
1 | class Solution(object): |