標籤:
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.
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
https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
樹的按層遍曆,其實就是bfs。
維護一個隊列放每一層的節點,在每一輪中,把這一層的節點按照順序連起來。
因為是樹的結構,訪問過的節點不會再訪問,不需要bfs的visited對象。
Populating Next Right Pointers in Each Node II同樣的代碼就能過,但是II要求不能用額外的空間。
1 /** 2 * Definition for binary tree with next pointer. 3 * function TreeLinkNode(val) { 4 * this.val = val; 5 * this.left = this.right = this.next = null; 6 * } 7 */ 8 /** 9 * @param {TreeLinkNode} root10 * @return {void} Do not return anything, modify tree in-place instead.11 */12 var connect = function(root) {13 var queue = [];14 queue.push(root);15 bfs();16 17 function bfs(){18 if(queue.length > 0){19 var top = null;20 var newQueue = [];21 var preNode = null;22 while(top = queue.shift()){23 if(top.left){24 newQueue.push(top.left);25 if(preNode){26 preNode.next = top.left;27 }28 preNode = top.left;29 }30 if(top.right){31 newQueue.push(top.right);32 if(preNode){33 preNode.next = top.right;34 }35 preNode = top.right;36 }37 }38 if(preNode){39 preNode.next = null;40 }41 queue = newQueue;42 bfs();43 }44 }45 };
[LeetCode][JavaScript]Populating Next Right Pointers in Each Node