[Leetcode 117, Hard] Populating Next Right Pointers in Each Node II
来源:互联网 发布:护卫神php套件怎么用 编辑:程序博客网 时间:2024/06/06 18:58
Problem:
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
Analysis:
The non-recursive solution of 116 can be directly used in this solution. This is because that solution first group nodes by level and then populate the next pointer of each pointer.
Solutions:
C++:
void connect(TreeLinkNode *root) { if(root == NULL || (root->left == NULL && root->right == NULL)) return; queue<TreeLinkNode *> node_queue; node_queue.push(NULL); TreeLinkNode *p_cur = root; vector<TreeLinkNode *> node_level; while(p_cur || !node_queue.empty()) { if(p_cur) { if(p_cur->left) { node_queue.push(p_cur->left); node_level.push_back(p_cur->left); } if(p_cur->right) { node_queue.push(p_cur->right); node_level.push_back(p_cur->right); } } else { node_queue.push(NULL); for(int i = 0; i < node_level.size() - 1; ++i) node_level[i]->next = node_level[i + 1]; node_level.clear(); } p_cur = node_queue.front(); node_queue.pop(); } }Java:
Python:
0 0
- [Leetcode 117, Hard] 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 [117]
- LeetCode 117 Populating Next Right Pointers in Each Node II
- [leetcode 117] Populating Next Right Pointers in Each Node II
- [LeetCode 117]Populating Next Right Pointers in Each Node II
- leetcode || 117、Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II - LeetCode 117
- leetcode[117]:Populating Next Right Pointers in Each Node II
- Leetcode #117 Populating Next Right Pointers in Each Node II
- LeetCode 117: Populating Next Right Pointers in Each Node II
- LeetCode 117:Populating Next Right Pointers in Each Node II
- leetcode 117 Populating Next Right Pointers in Each Node II
- Leetcode 117 Populating Next Right Pointers in Each Node II
- LeetCode 117 Populating Next Right Pointers in Each Node II
- Leetcode-117: Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II (hard)
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- [leetcode] 209.Minimum Size Subarray Sum
- 文章标题
- 欢迎使用CSDN-markdown编辑器
- 1消息队列(报文队列)实践到内核消息队列的创建
- SQL复习
- [Leetcode 117, Hard] Populating Next Right Pointers in Each Node II
- 我是菜鸟:Java中接口/内部类中容易忽略的问题总结
- 关于oracle数据库的重新安装
- linux 小记
- 序列化
- JAVA环境搭建之JDK配置
- ubtuntu安装ssh服务
- 动态规划求解数组连续最大和
- mysql 性能优化