Populating Next Right Pointers in Each Node @ LeetCode (Python)
2014年3月21日 18:11
用一个队列实现按层遍历二叉树。遇到第1, 3, 7, 15, 31...个节点时(都和2的幂有关)让它们的next指向空, 判断N是不是1, 3, 7, 15, 31...的公式是 N & (N + 1) == 0, 位运算。
Use a queue to traverse the binary tree by level. When we meet the 1st, 3rd, 7th, 15th, 31th... node (note that they are close to 2^n), assign None to their "next" field. Bit operation can be used to check whether N is 1, 3, 7, 15, 31... or not. N & (N + 1) == 0