class Node
{
public:
int val;
Node *left;
Node *right;
Node *next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node *_left, Node *_right, Node *_next)
: val(_val), left(_left), right(_right), next(_next) {}
};
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
void connectWoNode(Node *node1, Node *node2)
{
if (node1 == nullptr || node2 == nullptr)
{
return;
}
node1->next = node2;
connectWoNode(node1->left, node1->right);
connectWoNode(node2->left, node2->right);
connectWoNode(node1->right, node2->left);
}
Node *connect(Node *root)
{
if (root == nullptr)
{
return nullptr;
}
root->next = nullptr;
connectWoNode(root->left, root->right);
return root;
}
};
package main
type Node struct {
Val int
Left *Node
Right *Node
Next *Node
}
func connect(root *Node) *Node {
if root == nil {
return nil
}
var dfs func(*Node, *Node)
dfs = func(node1 *Node, node2 *Node) {
if node1 == nil || node2 == nil {
return
}
node1.Next = node2
dfs(node1.Left, node1.Right)
dfs(node2.Left, node2.Right)
dfs(node1.Right, node2.Left)
}
dfs(root.Left, root.Right)
return root
}