Populating Next Right Pointers in Each Node I
一、题目说明
如图所说,将二叉树中每一层作指向。
二、解题思路
按层级遍历树的节点,使得横向前节点指向后节点。然后再从下一层第一个节点开始,直到每一层都遍历结束。
三、java代码
/**
* 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) {
TreeLinkNode level_start = root;
while(level_start != null) {
//记录level_start的首个节点,以便于遍历下一层
TreeLinkNode cur = level_start;
while(level_start != null) {
if(level_start.left != null) {
level_start.left.next = level_start.right;
}
if(level_start.right != null && level_start.next != null) {
level_start.right.next = level_start.next.left;
}
level_start = level_start.next;
}
level_start = cur.left;
}
}
}
Populating Next Right Pointers in Each Node II
一、题目说明
如 I 中所说,II 中说树为任意二叉树。
二、解题思路
思路跟上一道题一样,按层级遍历树的节点,使得横向前节点指向后节点。然后再从下一层第一个节点开始,直到每一层都遍历结束。
但是不一样的是每一层的开始节点不保证是level_start.left;下一层的第一个节点具有不确定性,所以需要引入dummy节点。
三、java代码
/**
* 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) {
TreeLinkNode level_start = root;
while(level_start != null) {
//下一层的首个节点
TreeLinkNode dummy = new TreeLinkNode(0);
TreeLinkNode cur = dummy;
while(level_start != null) {
if(level_start.left != null) {
cur.next = level_start.left;
cur = cur.next;
}
if(level_start.right != null) {
cur.next = level_start.right;
cur = cur.next;
}
level_start = level_start.next;
}
level_start = dummy.next;
}
}
}