Populating Next Right Pointers in Each Node
2014-08-26 16:18
288 查看
题意:Given a binary tree
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
Initially, all next pointers are set to
思路:看到这道题,很容易想到利用层序遍历的思想,得到每层节点的所有左右子节点,然后指向。
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.
思路:看到这道题,很容易想到利用层序遍历的思想,得到每层节点的所有左右子节点,然后指向。
class Solution { public: void connect(TreeLinkNode *root) { /***************************************** * 队列的长度最好取10000以上,前面WA是因为队列的长度太小了 * ****************************************/ TreeLinkNode* Q[10000]; int front = 0, rear = -1; int i; Q[++rear] = root; if (Q[rear] == NULL) { return; } int index; while(front <= rear) { index = rear; for(i = front; i <= index; i++) { if (Q[i]->left != NULL) { Q[++rear] = Q[i]->left; Q[rear]->next = Q[i]->right; } if (Q[i]->right != NULL) { Q[++rear] = Q[i]->right; Q[rear]->next = (i+1<=index) ? Q[i+1]->left : NULL; } } front = index + 1; } } };
相关文章推荐
- leetcode Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- LeetCode - Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node
- 5.4.6 Populating Next Right Pointers in Each Node
- Leetcode-populating-next-right-pointers-in-each-node
- LeetCode: Populating Next Right Pointers in Each Node 解题报告
- [Leetcode]Populating Next Right Pointers in Each Node
- [Leetcode] Populating Next Right Pointers in Each Node II
- [leetcode] Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node II -- LeetCode
- Leetcode 116 Populating Next Right Pointers in Each Node
- Leetcode: Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- [116]Populating Next Right Pointers in Each Node
- LeetCode——Populating Next Right Pointers in Each Node II
- 116. Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node -- leetcode