LeetCode题解:Populating Next Right Pointers in Each Node
2015-10-02 21:01
561 查看
Given a binary tree
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
题意:让给定二叉树的每一层的结点从左到右指向它的右结点,最右边的结点则指向NULL
解决思路:层序遍历
代码:
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
题意:让给定二叉树的每一层的结点从左到右指向它的右结点,最右边的结点则指向NULL
解决思路:层序遍历
代码:
public class Solution { public void connect(TreeLinkNode root) { while (root != null) { TreeLinkNode curr = root; while (curr != null && curr.left != null) { curr.left.next = curr.right; curr.right.next = curr.next == null ? null : curr.next.left; curr = curr.next; } root = root.left; } } }
相关文章推荐
- Node.js第三方模块之htmlparser2
- 【nodemailer】 之邮件附件
- Node.js第三方库之request
- Swap Nodes in Pairs and Reverse Nodes in k-Group
- 【nodemailer】 初试
- Node.js第三方模块之download
- hadoop namenode无法启动,提示Failed on local exception的解决方法
- Node.js第三方模块之download-cli
- node起步
- Node express框架初试
- windows下安装node.js及less
- [Leetcode]Swap Nodes in Pairs
- Reverse Nodes in k-Group
- **LeetCode-Count Complete Tree Nodes
- nodejs学习笔记二:闭包和异步编程
- nodejs学习笔记一:什么是事件驱动编程风格
- LeetCode---Swap Nodes in Pairs
- nodejs vim 配置
- node.js下LDAP查询实例分享
- [LeetCode] Delete Node in a Linked List