博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【一天一道LeetCode】#116. Populating Next Right Pointers in Each Node
阅读量:4197 次
发布时间:2019-05-26

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

一天一道LeetCode

本系列文章已全部上传至我的github,地址:

欢迎大家关注我的新浪微博,
欢迎转载,转载请注明出处

(一)题目

来源:

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

(二)解题

题目大意:定义一个新的二叉树结构,增加一个新指针next指向该节点右侧相邻的节点。

解题思路:考虑到要指向右侧相邻的节点,可以采用层序遍历的方式来求解
将每一层的节点用next连接起来即可!
层序遍历可以参考:
废话不说,看AC代码:

/** * 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) {        if(root==NULL) return;        queue
myque; myque.push(root); while(!myque.empty()) { queue
temp_que; TreeLinkNode *pre = NULL; while(!myque.empty()) { TreeLinkNode *temp = myque.front(); myque.pop(); if(pre==NULL) pre = temp;//相当于每一层的头节点 else { pre->next = temp;//用next指针连接每一层的节点 pre = temp; } if(temp->left!=NULL) temp_que.push(temp->left);//下一层 if(temp->right!=NULL) temp_que.push(temp->right);//下一层 } pre->next=NULL;//最后一个节点的next需要指向NULL myque=temp_que;//进入下一层操作 } }};
你可能感兴趣的文章
LoadRunner测试GWT
查看>>
负载测试项目成功的5个关键要素
查看>>
LoadRunner性能测试培训大纲
查看>>
LoadRunner测试J2ME的Socket程序
查看>>
《QTP自动化测试实践》要出第二版了!
查看>>
用LoadRunner开发开心网外挂
查看>>
QTP测试.NET控件CheckedListBox
查看>>
使用QTP的.NET插件扩展技术测试ComponentOne的ToolBar控件
查看>>
用上帝之眼进行自动化测试
查看>>
为LoadRunner写一个lr_save_float函数
查看>>
PrefTest工作室全新力作-《性能测试与调优实战》课程视频即将上线
查看>>
质量度量分析与测试技术 培训大纲
查看>>
欢迎加入【亿能测试快讯】邮件列表!
查看>>
为什么我们的自动化测试“要”这么难
查看>>
LoadRunner性能脚本开发实战训练
查看>>
测试之途,前途?钱途?图何?
查看>>
测试设计与测试项目实战训练
查看>>
HP Sprinter:敏捷加速器
查看>>
IDC 的调查发现开发人员的37%的时间花在解决BUG上
查看>>
单元测试培训PPT
查看>>