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

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

标题:
通过率: 36.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 这个题目我感觉没必要一定是满二叉树,按层次遍历一遍。然后进行链表连接,需要注意的就是边界问题。开头和结尾的处理方法。 具体看代码
1 /** 2  * Definition for binary tree with next pointer. 3  * public class TreeLinkNode { 4  *     int val; 5  *     TreeLinkNode left, right, next; 6  *     TreeLinkNode(int x) { val = x; } 7  * } 8  */ 9 public class Solution {10     public void connect(TreeLinkNode root) {11         int count=1,tmp=0;12         LinkedList
queue=new LinkedList
();13 TreeLinkNode start=null,sec=null,pre=null;14 if(root!=null){15 queue.addLast(root);16 }17 while(!queue.isEmpty()){18 pre=queue.pollFirst();19 if(count==1)pre.next=null;20 if(pre.left!=null){21 queue.addLast(pre.left);22 tmp++;23 }24 if(pre.right!=null){25 queue.addLast(pre.right);26 tmp++;27 }28 29 for(int i=1;i

 

转载于:https://www.cnblogs.com/pkuYang/p/4334761.html

你可能感兴趣的文章
Shell脚本之Mysql授权
查看>>
开始写博客了
查看>>
SCCM 2007 实现PXE要点
查看>>
[转载]Windows和Linux双系统下完美卸载linux
查看>>
oracle:检查操作系统版本: 必须是 XXX 未通过
查看>>
python中的行结构和缩进
查看>>
Linux 基于openssl的https服务配置
查看>>
磨刀不误砍柴工 建站前选好虚拟主机是关键
查看>>
sed命令小总结(一)
查看>>
遇到的vSphere Client无法连接vSphere server的问题
查看>>
我的友情链接
查看>>
Ubuntu 配置JDK
查看>>
八款开源 Android 游戏引擎 (巨好的资源)
查看>>
lnmp源码安装
查看>>
数据库事务基础知识
查看>>
javascript面向对象与原型
查看>>
SubVersion与MyEclipse整合
查看>>
ftp被动模式
查看>>
redis数据库安装配置
查看>>
英语学习网站
查看>>