标签:需要 nec 指针 admin bin tor each .com nbsp
Description Submission Solutions Add to List
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:
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
Solution 1:添加空指针来分层
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { queue<TreeLinkNode*> q; if(!root) return; q.push(root); q.push(NULL);//比层序遍历多了要push NULL进去 //while(!q.empty()){ while(true){ //int size = q.size(); //for(int i = 0; i < size; i++){ TreeLinkNode* tmp = q.front(); q.pop(); if(tmp){ tmp -> next = q.front(); if(tmp -> left) q.push(tmp -> left); if(tmp -> right) q.push(tmp -> right); }else{ if(q.size() == 0 || q.front() == NULL) return;//添加空指针NULL来达到分层的目的,使每层的最后一个节点的next可以指向NULL q.push(NULL); } //} } } };
Solution 2:记录size来分层
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { queue<TreeLinkNode*> q; if(!root) return; q.push(root); while(!q.empty()){ int size = q.size(); for(int i = 0; i < size; i++){ TreeLinkNode* tmp = q.front(); q.pop(); if(i < size - 1){//给直到每层的倒数第二个node设置next指针 tmp -> next = q.front(); } //tmp -> next = q.front(); if(tmp -> left) q.push(tmp -> left); if(tmp -> right) q.push(tmp -> right); } } } };
Solution 3:Recursion
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */ class Solution { public: void connect(TreeLinkNode *root) { if(!root) return; if(root -> left){ root -> left -> next = root -> right; } if(root -> right){ root -> right -> next = root -> next ? root -> next -> left : NULL;//需要判断root -> next是否为空,否则空指针是没有左指针的 } connect(root -> left); connect(root -> right); } };
【56】116. Populating Next Right Pointers in Each Node
标签:需要 nec 指针 admin bin tor each .com nbsp
原文地址:http://www.cnblogs.com/93scarlett/p/6390417.html