首页 技术 正文
技术 2022年11月17日
0 收藏 939 点赞 2,264 浏览 1484 个字

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

问题: 给定一个二叉树,将树元素的 *next 指向该元素在树结构中的水平右边节点。

这是广度遍历的一个应用。可以借组队列结构实现广度遍历,求解题目。

思路:

  • 当队列中元素恰好是树种某一行的全部元素时,则给队列中每个节点的 *next 赋值为 列表中对应的下一个节点,其中特别地,最后一个元素*next 为 NULL。
  • 将队列中的元素全部弹出,并依次塞进他们的子节点,此时,队列中的元素恰好是树种下一行的全部元素,继续上一步操作。

将根节点塞进队列,即实现了上面思路的初始化。

     void connect(TreeLinkNode *root) {         if(root == NULL){
return;
} list<TreeLinkNode*> queue; queue.push_back(root); while(queue.size() > ){ // assign value to the next point of the node in queue.
list<TreeLinkNode*>::iterator q_iter;
for( q_iter = queue.begin() ; std::next(q_iter,) != queue.end(); q_iter++){
(*q_iter)->next = *std::next(q_iter,);
} // pop each node in the current row in the tree structure, and push the left and right childrens of them into queue.
while(queue.front()->next != NULL){
TreeLinkNode* node = queue.front();
queue.pop_front(); if(node->left != NULL){
queue.push_back(node->left);
} if(node->right != NULL){
queue.push_back(node->right);
}
} TreeLinkNode* node = queue.front();
queue.pop_front(); if(node->left != NULL){
queue.push_back(node->left);
} if(node->right != NULL){
queue.push_back(node->right);
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,083
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,558
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,407
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,180
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,816
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,899