Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 86 additions & 0 deletions 33. Flatten Binary Tree to Linked List.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
TreeNode* prev = NULL;

public:
void flatten(TreeNode* root) {

/*
// Recursive Aproach:

if(root == NULL) return;

flatten(root->right);
flatten(root->left);

root->right = prev;
root->left = NULL;

prev = root;
*/

/*
// Iterative Approach

if(root == NULL) return;

stack<TreeNode*> st;
st.push(root);

while(!st.empty()) {

TreeNode* curr = st.top();
st.pop();

if(curr->right) st.push(curr->right);
if(curr->left) st.push(curr->left);

if(st.empty() == false) {
curr->right = st.top();
}

curr->left = NULL;

}
*/


// Morris Traversal Approach

if(root == NULL) return;

TreeNode* curr = root;

while(curr != NULL) {

if(curr->left) {
TreeNode* prev = curr->left;

while(prev->right) {
prev = prev->right;
}

prev->right = curr->right;
curr->right = curr->left;
curr->left = NULL;

}

curr = curr->right;

}



}
};
63 changes: 63 additions & 0 deletions 38. Delete Node in a BST.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
private:
TreeNode* helper(TreeNode* root) {
if(root->left == NULL) { // no left subtree
return root->right;
}
else if(root->right == NULL) { // no right subtree
return root->left;
}

TreeNode* rchild = root->right;
TreeNode* lastRightofLeft = findLastRight(root->left);
lastRightofLeft->right = rchild;

return root->left;
}

TreeNode* findLastRight(TreeNode* root) {
while(root->right != NULL) root = root->right;

return root;
}
public:
TreeNode* deleteNode(TreeNode* root, int key) {
if(root == NULL) return NULL;
else if(key == root->val) {
return helper(root);
}

TreeNode* tmp = root;

while(root != NULL) {
if(root->val > key) {
if(root->left != NULL && root->left->val == key) {
root->left = helper(root->left);
break;
}
else root = root->left;
}

else {
if(root->right != NULL && root->right->val == key) {
root->right = helper(root->right);
break;
}
else root = root->right;
}
}

return tmp;
}
};