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

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

Populating Next Right Pointers in Each Node

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

/**

* 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;
    subconnect(root.left, root.right);
  }
  private void subconnect(TreeLinkNode left, TreeLinkNode right){
    if(left == null && right == null) return;
    left.next = right;
    subconnect(left.left, left.right);
    subconnect(right.left, right.right);
    subconnect(left.right, right.left);
  }
}

转载于:https://www.cnblogs.com/boole/p/3639321.html

你可能感兴趣的文章
面向对象编程基础 (二)
查看>>
MVC的请求过程(或者MVC三者的关系)
查看>>
网页设计易错点总结
查看>>
assign-cookies
查看>>
<正则吃饺子> :关于redis配置文件参数详解
查看>>
2018-2019-2 20165334-Exp6:信息收集与漏洞扫描
查看>>
python发邮件模板参考
查看>>
【转载】rpc.rstatd安装与配置
查看>>
新东方雅思词汇---10.1、(a)esthet
查看>>
html常用属性border-radius、linear-gradient怎么使用
查看>>
jquery-12 折叠面板如何实现(两种方法)
查看>>
bootstrap课程10 从外部引入视频到页面用什么标签
查看>>
m_Orchestrate learning system---二十一、怎样写算法比较轻松
查看>>
贪心3--删数问题
查看>>
handler消息机制入门
查看>>
二维数组
查看>>
第十周作业
查看>>
阅读笔记《构建之法》五
查看>>
SQL 高级查询
查看>>
LIUNX-Centos 7 编译GDAL
查看>>