|
| 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 | +/** |
| 10 | + *@param {TreeLinkNode} root |
| 11 | + *@return {void} Do not return anything, modify tree in-place instead. |
| 12 | + */ |
| 13 | +// BFS, level order Traversal, set a dummy head at the beginnig of each level. |
| 14 | +// Is it O(1) space? |
| 15 | +varconnect=function(root){ |
| 16 | +while(root){ |
| 17 | +varleftDummy=newTreeLinkNode(0); |
| 18 | +varcurrChild=leftDummy; |
| 19 | +while(root){ |
| 20 | +if(root.left){ |
| 21 | +currChild.next=root.left; |
| 22 | +currChild=currChild.next; |
| 23 | +} |
| 24 | +if(root.right){ |
| 25 | +currChild.next=root.right; |
| 26 | +currChild=currChild.next; |
| 27 | +} |
| 28 | +root=root.next; |
| 29 | +} |
| 30 | +// reset head to the left of each level. |
| 31 | +root=leftDummy.next; |
| 32 | +} |
| 33 | +}; |
| 34 | + |
| 35 | + |
| 36 | +/** |
| 37 | + * Definition for binary tree with next pointer. |
| 38 | + * function TreeLinkNode(val) { |
| 39 | + * this.val = val; |
| 40 | + * this.left = this.right = this.next = null; |
| 41 | + * } |
| 42 | + */ |
| 43 | + |
| 44 | +// BFS too, but constant space |
| 45 | +varconnect=function(root){ |
| 46 | +// next level's head (beginnig) |
| 47 | +varhead=root; |
| 48 | +// next level's last visited node |
| 49 | +varprev; |
| 50 | +// curr level's currently visiting node |
| 51 | +varcurr; |
| 52 | +while(head){ |
| 53 | +curr=head; |
| 54 | +prev=null; |
| 55 | +head=null; |
| 56 | +while(curr){ |
| 57 | +if(curr.left){ |
| 58 | +if(prev)prev.next=curr.left; |
| 59 | +elsehead=curr.left; |
| 60 | +prev=curr.left; |
| 61 | +} |
| 62 | +if(curr.right){ |
| 63 | +if(prev)prev.next=curr.right; |
| 64 | +elsehead=curr.right; |
| 65 | +prev=curr.right; |
| 66 | +} |
| 67 | +curr=curr.next; |
| 68 | +} |
| 69 | +} |
| 70 | +}; |
| 71 | + |
| 72 | +// doesn't work, wrong answer. e.g. {1,2,3,4,5,#,6,7,#,#,#,#,8}, |
| 73 | +// the common parent is one more level up |
| 74 | +varconnect=function(root){ |
| 75 | +if(!root)return; |
| 76 | + |
| 77 | +while(root){ |
| 78 | +varpNode=root; |
| 79 | +while(pNode){ |
| 80 | +varchild=null; |
| 81 | +if(pNode.left&&pNode.right){ |
| 82 | +pNode.left.next=pNode.right; |
| 83 | +child=pNode.right; |
| 84 | +}else{ |
| 85 | +if(pNode.left)child=pNode.left; |
| 86 | +if(pNode.right)child=pNode.right; |
| 87 | +} |
| 88 | +if(child){ |
| 89 | +if(pNode.next){ |
| 90 | +if(pNode.next.left)child.next=pNode.next.left; |
| 91 | +elsechild.next=pNode.next.right; |
| 92 | +} |
| 93 | +} |
| 94 | +pNode=pNode.next; |
| 95 | +} |
| 96 | + |
| 97 | +while(root&&!root.left&&!root.right){ |
| 98 | +root=root.next; |
| 99 | +} |
| 100 | +if(!root)break; |
| 101 | +if(root.left)root=root.left; |
| 102 | +elseif(root.right)root=root.right; |
| 103 | +} |
| 104 | +}; |