首页 技术 正文
技术 2022年11月9日
0 收藏 797 点赞 4,018 浏览 1492 个字

给定一个二叉树
    struct TreeLinkNode {
      TreeLinkNode *left;
      TreeLinkNode *right;
      TreeLinkNode *next;
    }
填充他的每个 next(下一个)指针,让这个指针指向其下一个右侧节点。如果找不到下一个右节点,则应该将 next(下一个)指针设置为 NULL。
初始状态下,所有 next(下一个)指针 都被设置为 NULL。
注意事项:
    您只能使用恒定的额外空间。
    你可以假设它是一棵完美二叉树(即所有叶子都在同一水平上,每个父节点有两个孩子)。
例如,鉴于以下完美二叉树,
         1
       /  \
      2    3
     / \  / \
    4  5  6  7
调用你的函数后,该树应该变成这样:
         1 -> NULL
       /  \
      2 -> 3 -> NULL
     / \  / \
    4->5->6->7 -> NULL

详见:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/description/

Java实现:

递归实现:

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null){
return;
}
if(root.left!=null){
root.left.next=root.right;
}
if(root.right!=null){
root.right.next=root.next!=null?root.next.left:null;
}
if(root.left!=null){
connect(root.left);
}
if(root.right!=null){
connect(root.right);
}
}
}

非递归实现:

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null){
return;
}
LinkedList<TreeLinkNode> que=new LinkedList<TreeLinkNode>();
que.offer(root);
while(!que.isEmpty()){
//记录本层节点的个数
int size=que.size();
for(int i=0;i<size;++i){
TreeLinkNode cur=que.poll();
//最后一个节点的next是null,不做处理
if(i<size-1){
TreeLinkNode next=que.peek();
cur.next=next;
}
if(cur.left!=null){
que.offer(cur.left);
}
if(cur.right!=null){
que.offer(cur.right);
}
}
}
}
}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,494
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,495
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,133
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,297