[LeetCode] Populating Next Right Pointers in Each Node
文章目录
Populating Next Right Pointers in Each Node
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.
BFS
Time Complexity
O(N)
Space Complexity
O(N)
思路
Because it is a perfect binary tree. So we use a queue to keep every level. Initialize a node called pre, if it is the first node in this level, make pre equals current first node, if it is not, then pre.next = cur. When this level of bfs ends, this level's nodes are all connected.
代码
public void connect(TreeLinkNode root) {
//corner case
if(root == null) return;
Queue<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
queue.offer(root);
TreeLinkNode pre = null;
while(!queue.isEmpty()){
int size = queue.size();
for(int i = 0; i < size; i++){
TreeLinkNode cur = queue.poll();
if(cur.left != null) queue.offer(cur.left);
if(cur.right != null) queue.offer(cur.right);
if(pre != null){
pre.next = cur;
}
pre = cur;
}
pre = null;
}
}
Populating Next Right Pointers in Each Node II
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?
My previous solution still works. :)
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论