leetcode Populating Next Right Pointers in Each Node
2017-02-01 22:21
411 查看
这道题直观的思路是采用层序遍历,在每次换行的时候进行一次处理,不换行的时候直接连接当前节点和他右边的兄弟即可,使用两个变量来标示换行。
Not signed i
Not signed i
/** * 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) { int nextLevel = 0; //下一层需要访问几个节点 int tobePrint = 1; //还需访问几个节点 queue<TreeLinkNode*> q; if(root == NULL) return; q.push(root); while(!q.empty()) { TreeLinkNode* curNode = q.front(); if(curNode -> left != NULL) { nextLevel++; q.push(curNode -> left); } if(curNode -> right != NULL) { nextLevel++; q.push(curNode -> right); } q.pop(); tobePrint--; if(tobePrint == 0) //当前行的最后一个节点 { curNode -> next = NULL; tobePrint = nextLevel; nextLevel = 0; } else { curNode -> next = q.front(); } } } };
Not signed i
Not signed i
相关文章推荐
- [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
- 【leetcode】Populating Next Right Pointers in Each Node II
- 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 79: Populating Next Right Pointers in Each Node II
- LeetCode: Populating Next Right Pointers in Each Node
- [LeetCode] Populating Next Right Pointers in Each Node
- LeetCode(Oct28'12):Populating Next Right Pointers in Each Node II
- [LeetCode]Populating Next Right Pointers in Each Node
- leetcode 78: Populating Next Right Pointers in Each Node
- [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
- leetcode Populating Next Right Pointers in Each Node II
- [Leetcode]Populating Next Right Pointers in Each Node II
- leetcode 79: Populating Next Right Pointers in Each Node II