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
题目链接:https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
题目分析:从根往下连就好了,因为是满二叉树,很多地方不用做判断,比如说同层当前点有左孩子,那表示它肯定有右孩子并且它指向的next结点不为空,那指向的next结点也肯定有左孩子和右孩子,所以只需要判断当前点指向的next是否为空即可
/**
* 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;
}
while (root.left != null) {
for (TreeLinkNode cur = root; cur != null; cur = cur.next) {
//当前节点的左孩子的next指向右孩子
cur.left.next = cur.right;
if (cur.next != null) {
//当前结点的右孩子的next指向其next结点的左孩子
cur.right.next = cur.next.left;
}
}
root = root.left;
}
}
}

本文介绍了一种在满二叉树中填充每个节点的next指针的方法,使其指向右侧相邻节点。通过迭代方式实现,仅使用常数额外空间。
282

被折叠的 条评论
为什么被折叠?



