1 // 主函数
2 Node connect(Node root) {
3 //--主函数可以解决:
4 //--用递归函数遍历左右节点时,
5 //--root节点必定是完全没有兄弟节点的特殊情况,
6 //--将root节点独立处理
7 if (root == null) return null;
8 connectTwoNode(root.left, root.right);
9 return root;
10 }
11
12 // 辅助函数
13 //--辅助函数即递归函数的主体
14 void connectTwoNode(Node node1, Node node2) {
15 //--二叉树的NULL节点直接用return结束,即忽略NULL节点的处理
16 if (node1 == null || node2 == null) {
17 return;
18 }
19
20 /**** 前序遍历位置 ****/
21 // 连接传入的两个节点
22 node1.next = node2;
23
24 // 连接相同父节点的两个子节点
25 connectTwoNode(node1.left, node1.right);
26 connectTwoNode(node2.left, node2.right);
27
28 // *********************连接跨越父节点的两个子节点
29 connectTwoNode(node1.right, node2.left);
30 }
31 //--使用递归处理分层的树的时候,可以通过:指明递归函数中的跨层操作的对象,再使用递归函数处理该对象,即可遍历该跨层对象,例:29行中的两个参数