Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit668052e

Browse files
Add C++ implementation
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent5fd56b7 commit668052e

File tree

2 files changed

+52
-9
lines changed

2 files changed

+52
-9
lines changed

‎0116_populating_next_right_pointers_in_each_node/connect.c‎

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,35 @@
11
#include<stdio.h>
22
#include<stdlib.h>
33

4-
structTreeLinkNode {
4+
5+
structNode {
56
intval;
6-
structTreeLinkNode*left;
7-
structTreeLinkNode*right;
8-
structTreeLinkNode*next;
7+
structNode*left;
8+
structNode*right;
9+
structNode*next;
910
};
1011

11-
staticvoidconnect(structTreeLinkNode*root)
12+
structNode*connect(structNode*root)
1213
{
1314
if (root==NULL) {
14-
return;
15+
returnroot;
1516
}
1617

17-
structTreeLinkNode*head=root;
18+
structNode*head=root;
1819
while (head->left!=NULL) {
19-
structTreeLinkNode*p;
20+
structNode*p;
2021
for (p=head;p!=NULL;p=p->next) {
2122
p->left->next=p->right;
2223
p->right->next=p->next==NULL ?NULL :p->next->left;
2324
}
2425
head=head->left;
2526
}
27+
returnroot;
2628
}
2729

2830
intmain(intargc,char**argv)
2931
{
30-
structTreeLinkNoderoot,n1[2],n2[4],n3[8];
32+
structNoderoot,n1[2],n2[4],n3[8];
3133
root.val=5;
3234
n1[0].val=4;
3335
n1[1].val=8;
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#include<stdc++.h>
2+
3+
usingnamespacestd;
4+
5+
/*
6+
// Definition for a Node.
7+
class Node {
8+
public:
9+
int val;
10+
Node* left;
11+
Node* right;
12+
Node* next;
13+
14+
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
15+
16+
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
17+
18+
Node(int _val, Node* _left, Node* _right, Node* _next)
19+
: val(_val), left(_left), right(_right), next(_next) {}
20+
};
21+
*/
22+
23+
classSolution {
24+
public:
25+
Node*connect(Node* root) {
26+
if (root ==nullptr) {
27+
return root;
28+
}
29+
30+
if (root->left !=nullptr) {
31+
root->left->next = root->right;
32+
}
33+
Node *next = root->next;
34+
if (root->right !=nullptr && next !=nullptr) {
35+
root->right->next = next->left;
36+
}
37+
connect(root->left);
38+
connect(root->right);
39+
return root;
40+
}
41+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp