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?
Note:
- You may only use constant extra space. 
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
题意:把每一层节点链接起来
思路:层次遍历的思想,将一层的元素全部入队,然后将本层每个节点的子节点一次全部入队
- class Solution 
- { 
- public: 
- void connect(TreeLinkNode* root) 
- { 
- if (root==NULL) 
- { 
- return; 
- } 
- TreeLinkNode* tail = root; 
- TreeLinkNode* tmp; 
- queue<TreeLinkNode*> q; 
- q.push(root); 
- while (q.size()) 
- { 
- tmp = q.front(); 
- q.pop(); 
- if (tmp->left!=NULL) 
- { 
- q.push(tmp->left); 
- } 
- if (tmp->right!=NULL) 
- { 
- q.push(tmp->right); 
- } 
- if(tmp==tail) 
- { 
- tmp->next = NULL; 
- tail = q.back(); 
- } 
- else 
- { 
- tmp->next = q.front(); 
- } 
- } 
- } 
- }; 

 
					
				
 
			
			
			
						
			 我要赚赏金
 我要赚赏金 STM32
STM32 MCU
MCU 通讯及无线技术
通讯及无线技术 物联网技术
物联网技术 电子DIY
电子DIY 板卡试用
板卡试用 基础知识
基础知识 软件与操作系统
软件与操作系统 我爱生活
我爱生活 小e食堂
小e食堂

