LeetCode:Populating Next Right Pointers in Each Node
来源:互联网 发布:手机淘宝找不到店铺 编辑:程序博客网 时间:2024/05/31 11:04
问题描述:
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:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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
思路:首先想到的是BFS。但是BFS需要借助队列,这样就不能满足题目空间复杂度的要求。难点在于如何不用多余的空间完成树的遍历。解决这个问题需要用到树节点结构中包含的next域。可以借助next完成不用队列的BFS。
代码:
void Solution::connect(TreeLinkNode * root){ if(root == NULL) return; TreeLinkNode * cur; while(root->left != NULL)//当root->left为NULL时,表示已经遍历到了最后一层,此时已经完成了所有next的赋值 { cur = root;//在遍历每一层时,cur指针用来指向当前所要处理的节点 while(cur != NULL)//cur为NULL时,表示当前这一层已经处理完 { if(cur->left != NULL) cur->left->next = cur->right;//当前节点左子节点的next域指向当前节点的右子节点 if(cur->next != NULL) cur->right->next = cur->next->left;//当前节点的右子节点的next域指向当前节点next域所指节点的左子节点 cur = cur->next; } root = root->left;//开始处理下一层 }}
0 0
- 【LeetCode】Populating Next Right Pointers in Each Node Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node &&Populating Next Right Pointers in Each Node||
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- 【Leetcode】Populating Next Right Pointers in Each Node in JAVA
- 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 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 78: 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 ii
- leetcode Populating Next Right Pointers in Each Node II
- 【leetcode】Populating Next Right Pointers in Each Node
- iOS 横竖屏
- directX视频播放------手动连接
- 杂(二): "** cannot be resolved to a type "eclipse报错及解决
- jQuery map将一个数组中的元素转换到另一个数组中
- 二维码扫描仪
- LeetCode:Populating Next Right Pointers in Each Node
- 使用Ant 实现批量打包Android应用
- C语言中的输入输出是怎样的及怎么使用怎么扩展
- Cookie/Session机制详解
- XmlTextWriter学习笔记
- 利用jsoup爬取百度网盘资源分享连接(多线程)
- ant教程详解--javac,java,jar,war,delete,copy,mkdir..
- CodeForces 12D Ball 多级排序 + 离散 + 线段树
- 关于百度地图iOS8的定位问题以及iPhone6 Plus黑框