LeetCode - Populating Next Right Pointers in Each Node
2024-08-28 02:53:17
题目:
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
思路:
递归,然后把中间的节点给连起来
package tree; class TreeLinkNode {
int val;
TreeLinkNode left, right, next;
TreeLinkNode(int x) { val = x; }
} public class PopulatingNextRightPointersInEachNode { public void connect(TreeLinkNode root) {
if (root == null) return;
connect(root.left);
connect(root.right);
TreeLinkNode left = root.left;
TreeLinkNode right = root.right;
while (left != null && right != null) {
left.next = right;
left = left.right;
right = right.left;
}
} }
最新文章
- QT5.1 调用https
- 支付宝alipay使用小结 调用支付宝程序被杀死说明
- C#动态编译代码,执行一个代码片段,或者从指定文件中加载某个接口的实现类
- Debian下安装vim
- STL中的算法小结
- ecshop添加商品选择品牌时如何按拼音排序
- java语言基础02
- nginx1.8+php5.6.10 服务器编译安装备忘2015-06
- 基于Networks of Brokers的HA方案
- CodeForces 379 D. New Year Letter
- JAVA 命令参数详解System.setProperty(
- Python 用IMAP接收邮件
- iOS 之 导航栏按钮
- 将 MacOS 默认的 PHP 版本升级到 7.*
- 使用phpmailer插件发邮件失败提示:SMTP ->; ERROR: Failed to connect to server: Connection timed out (110) smtp connect() failed;
- springMVC源码分析--RequestMappingHandlerAdapter(五)
- HBuilderx中编译sass文件
- <;算法图解>;读书笔记:第1章 算法简介
- HDU - 3642 Get The Treasury(线段树求体积交)
- linux使用curl上传文件并且同时携带其它传递参数