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

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

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  * struct TreeLinkNode { 4  *  int val; 5  *  TreeLinkNode *left, *right, *next; 6  *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} 7  * }; 8  */ 9 class Solution {10 public:11     void connect(TreeLinkNode *root) {12        if (root == NULL) {13             return;14         }15         queue
q;16 TreeLinkNode *p;17 int idx = 1, n;18 q.push(root);19 while (!q.empty()) {20 n = idx - 1;21 idx = 0;22 p = q.front();23 if (q.front()->left != NULL) {24 q.push(q.front()->left);25 idx++;26 }27 if (q.front()->right != NULL) {28 q.push(q.front()->right);29 idx++;30 }31 q.pop();32 for (int i = 0; i < n; ++i) {33 p->next = q.front();34 if (q.front()->left != NULL) {35 q.push(q.front()->left);36 idx++;37 }38 if (q.front()->right != NULL) {39 q.push(q.front()->right);40 idx++;41 }42 p = p->next;43 q.pop();44 }45 p->next = NULL;46 } 47 }48 };

 

 

转载于:https://www.cnblogs.com/easonliu/p/3637003.html

你可能感兴趣的文章
SWT(JFace) Wizard(Eclipse插件编程必备)
查看>>
得力D991CN Plus计算器评测(全程对比卡西欧fx-991CN X)
查看>>
生物特征识别:小面积指纹识别算法(二)
查看>>
【c#基础知识大盲扫1】
查看>>
HDU-3473Minimum Sum
查看>>
Android学习4、Android该Adapter
查看>>
C#图片压缩处理
查看>>
Groovy新手教程
查看>>
【Unity 3D】学习笔记四十一:关节
查看>>
Struts2自己定义拦截器实例—登陆权限验证
查看>>
薏米红豆粥功效及做法介绍
查看>>
原型设计工具
查看>>
windows下的C++ socket服务器(4)
查看>>
css3 2d转换3d转换以及动画的知识点汇总
查看>>
python 正则指北之我的总结
查看>>
sql 简单的定义变量 声明 输出
查看>>
【Java】使用Eclipse进行远程调试,Linux下开启远程调试
查看>>
js对象属性方法
查看>>
转:JUnit使用指南
查看>>
C++面试题整理(持续更新中)
查看>>