LeetCode: Populating Next Right Pointers in Each Node II
2013-04-19 14:48
561 查看
这题关键是要记录下一层第一个节点
如果可以用extra space,可以用下面这段代码
/** * 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: TreeLinkNode *nextright(TreeLinkNode *root) { while (root) { if (root->left) return root->left; if (root->right) return root->right; root = root->next; } return NULL; } void connect(TreeLinkNode *root) { if (!root) return; TreeLinkNode *second, *first; first = root; second = NULL; first->next = NULL; while (first) { if (first->left) { if (!second) second = first->left; if (first->right) first->left->next = first->right; else first->left->next = nextright(first->next); } if (first->right) { if (!second) second = first->right; first->right->next = nextright(first->next); } first = first->next; if (!first) { first = second; second = NULL; } } } };
如果可以用extra space,可以用下面这段代码
/** * 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 *> S; if (!root) return; S.push(root); S.push(NULL); while (!S.empty()) { TreeLinkNode *front = S.front(); S.pop(); if (!front) continue; front->next = S.front(); if (front->left) S.push(front->left); if (front->right) S.push(front->right); if (!S.front()) S.push(NULL); } } };
相关文章推荐
- LeetCode 35 Populating Next Right Pointers in Each Node II
- LeetCode - 116/117 - Populating Next Right Pointers in Each NodeII
- leetcode - Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node II
- [LeetCode 116 117] - 填充每一个节点的指向右边邻居的指针I & II (Populating Next Right Pointers in Each Node I & II)
- [leetcode]Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node I & II
- [LeetCode] Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- leetcode:Populating Next Right Pointers in Each Node II
- LeetCode刷题笔录Populating Next Right Pointers in Each Node II
- Leetcode Populating Next Right Pointers in Each Node II
- [LeetCode]Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II [Leetcode]
- [leetcode] Populating Next Right Pointers in Each Node II
- [LeetCode#117]Populating Next Right Pointers in Each Node II
- [LeetCode] Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II ---LeetCode
- leetcode之Populating Next Right Pointers in Each Node II
- LeetCode - Populating Next Right Pointers in Each Node II