博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode—Populating Next Right Pointers in Each Node
阅读量:7225 次
发布时间:2019-06-29

本文共 1625 字,大约阅读时间需要 5 分钟。

1.题目描述

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

2.解法分析

这道题目给了一个很强的约束,那就是可以假设树结果为满二叉树,满二叉树每一层的节点个数是确定的,如果将树中的元素按照层序遍历的方式编号,那么编号为n的节点在哪一层也是轻易可知的(假设编号从1开始,那么节点n所在层为log2n+1),同样,每层最后一个节点的编号也是已知的(m层的最后一个元素编号为2m-1),基于这个强约束,我决定用层序遍历的方式解答这个题目。

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(root == NULL)return;
 
queue
q;
int count=0;
int depth =1;
TreeLinkNode * cur=NULL;
q.push(root);
while(!q.empty())
{
cur=q.front();
q.pop();
count++;
if(count == pow(2,depth)-1)
{
cur->next = NULL;
depth++;
}
 
else
{
cur->next = q.front();
}
 
if(cur->left!=NULL)q.push(cur->left);
if(cur->right!=NULL)q.push(cur->right);
}
 
 
}
};

代码一次通过,真爽!

转载于:https://www.cnblogs.com/obama/p/3252729.html

你可能感兴趣的文章
如何设计用户登录
查看>>
linux安装mysql5.7.19
查看>>
Zookeeper+ActiveMQ 集群实现
查看>>
加权有向图问题2----多源最短路径问题(Floyd算法)和关键路径算法
查看>>
logback logback.xml常用配置详解(三) <filter>
查看>>
KgMall B2B/B2B2c/C2C版店铺商号初始化
查看>>
Linux内核的ioctl函数学习
查看>>
Liunx Shell入门
查看>>
Thread的中断
查看>>
linux --- 内存管理
查看>>
PostgreSQL
查看>>
CPU 超线程、多核
查看>>
用ASCII码显示string.xml中的特殊字符
查看>>
网站301跳转到新域名
查看>>
codewars020: The Clockwise Spiral 数字顺时针螺旋矩阵
查看>>
ios 下拉刷新
查看>>
Django在Windows系统下的安装配置
查看>>
懒到极致:对mybatis的进一步精简
查看>>
Android学习之OTA Update
查看>>
Maven Multi-environment package
查看>>