今天学习的是二叉树中的算法题目:填充每个节点的下一个右侧节点指针。
题目介绍
给定一个满二叉树(所有叶子节点都在同一层,每个父节点都有两个叶子节点),填充它的next节点,指向下一个右侧节点,最右侧节点指向null。
看下图吧:
实现思路
直接看下图吧:
核心的逻辑是:节点的左节点的next为右节点,右节点的next为父节点的next节点的left节点。因此我们可以从root节点开始,先赋值节点的next,然后递归进入左节点和右节点。
实现代码
public class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {
}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
}
public class SolutionConnect {
public Node connect(Node root) {
if (null == root) {
return null;
}
if (null != root.left) {
root.left.next = root.right;
connect(root.left);
}
if (null != root.right) {
if (null != root.next) {
root.right.next = root.next.left;
}
connect(root.right);
}
return root;
}
}
算法相关实现源码地址:https://github.com/xiekq/rubs-algorithms