Populating Next Right Pointers in Each Node
来源:互联网 发布:mac页面如何放大 编辑:程序博客网 时间:2024/05/29 11:47
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
Tree Depth-first Search
题解:
1.每个节点的next都指向NULL;
2.使用有限的空间;
3.可假定它是完全二叉树。
思路:
递归方法。如下:
class Solution {public: void connect(TreeLinkNode *root) { if (root == NULL) return; TreeLinkNode *left, *right; left = root->left; right = root->right; if (left != NULL) left->next = right; /*右子数不空,则指向另一个父结点的左子树*/ if (right != NULL && root->next != NULL) right->next = root->next->left; connect(left); connect(right); }};
思路:
非递归之循环。如下:
void connect(TreeLinkNode *root) { if (root == NULL) return; TreeLinkNode *current; while (root->left){ //因为题目假设都为完全二叉树,此判断只需确定是否为叶子结点 current = root; while (current){ current->left->next = current->right; if (current->right && current->next) current->right->next = current->next->left; current = current->next; } root = root->left; } }
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- Populating Next Right Pointers in Each Node
- C语言文件操作 fopen, fclose, mkdir(打开关闭文件,建文件夹,判断文件是否存在可读或可写)
- iOS开发 剖析网易新闻标签栏视图切换(addChildViewController属性介绍)
- Hbase1.0 客户端api
- 没有营销,你的微商只是间背街门面 坐等关门
- 浅谈重定向和转发(理论篇)
- Populating Next Right Pointers in Each Node
- sdasd
- myLog.h
- jsp向action传值问题
- 关闭键盘的方法
- java中级-12-GUI图形用户界面(2)-GUI事件响应机制
- PHP命名空间(Namespace)的使用详解
- 总结下时间复杂度
- [翻译]Swift编程语言——关于Swift