Skip to content

Commit 998bf2c

Browse files
authored
Merge pull request #2389 from Ritesh7766/main
Create: 0876-middle-of-the-linked-list.cpp, 0094-binary-tree-inorder-traversal.cpp
2 parents d60c4f3 + c21aa84 commit 998bf2c

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* struct TreeNode {
4+
* int val;
5+
* TreeNode *left;
6+
* TreeNode *right;
7+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
8+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
9+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10+
* };
11+
*/
12+
#include <stack>
13+
14+
class Solution {
15+
public:
16+
/* Recursive
17+
vector<int> helper(TreeNode* node, vector<int>& path) {
18+
if (node == NULL)
19+
return path;
20+
21+
path = helper(node->left, path);
22+
path.push_back(node->val);
23+
path = helper(node->right, path);
24+
return path;
25+
}
26+
*/
27+
28+
// Iterative
29+
vector<int> inorderTraversal(TreeNode* root) {
30+
stack<TreeNode*> stk;
31+
vector<int> path;
32+
TreeNode* current = root;
33+
34+
while (!stk.empty() || current != NULL) {
35+
while (current != NULL) {
36+
stk.push(current);
37+
current = current->left;
38+
}
39+
TreeNode* node = stk.top();
40+
path.push_back(node->val);
41+
stk.pop();
42+
current = node->right;
43+
}
44+
return path;
45+
}
46+
};
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
12+
class Solution {
13+
public:
14+
ListNode* middleNode(ListNode* head) {
15+
/*
16+
The slow and fast pointer algorithm is used to find the middle
17+
of a linked list by iterating through the list with a slow
18+
pointer that moves one step at a time and a fast pointer that
19+
moves two steps at a time. When the fast pointer reaches the
20+
end of the list, the slow pointer will be at the midpoint of the list.
21+
*/
22+
ListNode *slow_pointer = head, *fast_pointer = head;
23+
while (fast_pointer != NULL && fast_pointer->next != NULL) {
24+
slow_pointer = slow_pointer->next;
25+
fast_pointer = fast_pointer->next->next;
26+
}
27+
return slow_pointer;
28+
}
29+
};

0 commit comments

Comments
 (0)