0% found this document useful (0 votes)
4 views

BST

binary search tree

Uploaded by

sayedul abrar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

BST

binary search tree

Uploaded by

sayedul abrar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

ts/stdc++.

h>
pace std;

Two binary trees are considered the same if


, level; structurally identical, and the nodes have t
eft, *right, *parent; value.
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q

if (!p && !q)


oot; return true;

if (!p || !q)
return false;
t = NULL;
if (p->val != q->val)
return false;
etRoot() {return root;}
return isSameTree(p->left, q->left)
isSameTree(p->right, q->right);
}
sert(int val){ };
e *x,*y,*z;
Node*)malloc(sizeof(Node));
key=val;
left=NULL; find the path with target as pathsum. WE can
right=NULL; a node end of the path if its both choldren
parent=NULL; did this way.
root==NULL) class Solution {
public:
root=z;
return; bool hasPathSum(TreeNode* root, int targ
if(root==NULL) return false;
oot; return hasPathSum2(root, targetSum);
ULL;
le(x!=NULL) }
bool hasPathSum2(TreeNode* root, int tar
if(val<x->key){ if (!root->left&&!root->right)
y=x; {
x=x->left; if(targetSum!=root->val) return
}else else return true;
{ }
y=x; bool ans=false;
x=x->right; if(root->left) ans+=hasPathSum2(root
} targetSum - root->val) ;
if(root->right) ans+=hasPathSum2(roo
targetSum - root->val);
parent=y; return ans;
z->key<y->key)
}
y->left=z; };
se

y->right=z;

class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
indNode(int val){ if (!root) return nullptr;//importan
de *n;
oot; TreeNode* left = invertTree(root->le
le(n!=NULL && n->key!=val) TreeNode* right = invertTree(root->r

if(val<n->key){ root->left = right;


root->right = left;
n=n->left;
}else return root;
{ }
n=n->right; };
}

}
return n;
// class Solution {
// public:
// void invertTree(TreeNode* root) {
// if (!root) return;
indMaximum(Node *node){
->right==NULL return node; // // Recursively invert the left an
findMaximum(node->right); subtrees
// invertTree(root->left);
// invertTree(root->right);

indMinimum(Node *node){ // // Swap the left and right childr


->left==NULL return node; // TreeNode* temp = root->left;
findMinimum(node->left); // root->left = root->right;
// root->right = temp;
// }
Order(Node *node){ // };
node==NULL) return;
rder(node->left);
t<<node->key<<" ";
rder(node->right); class Solution {
public:
bool isValidBST(TreeNode* root) {
return isValidBST(root, nullptr, nul
}

private:
eNode(Node* root, int key) { bool isValidBST(TreeNode* root, TreeNode
case: If the tree is empty or key not found TreeNode* maxNode) {
t == NULL) if (!root) return true;
urn root;
// if minnode,maxnode is set check v
< root->key) if ((minNode && root->val <= minNode
t->left = deleteNode(root->left, key); (maxNode && root->val >= maxNode->val))
(key > root->key) return false;
t->right = deleteNode(root->right, key);
// left subtree all<root
Node with only one child or no child // riht subtree all>root
(root->left == NULL) { return isValidBST(root->left, minNod
Node* temp = root->right; && isValidBST(root->right, root, maxNode);
if (temp) }
temp->parent = root->parent; // Update the };
ter of the child
free(root);
return temp;

e if (root->right == NULL) { Input


Node* temp = root->left; root =
if (temp) [1,2,5,3,4,null,6]
temp->parent = root->parent; // Update the Output
ter of the child [1,2,5,3,4,null,6]
free(root); Expected
return temp; [1,null,2,null,3,null,4,null,5,null,6]

class Solution {
e* temp = minValueNode(root->right); public:
t->key = temp->key; void flatten(TreeNode* root) {
t->right = deleteNode(temp, temp->key); // Base case: Empty tree
if (!root) {
root;// in else block returned value paoar por upore return;
continue rakhte aita dorkar. }

// Handle the left subtree recursive


ght(Node *node){ flatten(root->left);
node==NULL)
// Store the right subtree (importan
return -1; place modification)
se TreeNode* rightSubtree = root->right

return max(height(node->left),height(node->right)) // Set the right child to the flatte


subtree
root->right = root->left;

// Null out the left child (essentia


linked list structure)
root->left = nullptr;
ode*> q; //see the example below
evel = 0; TreeNode* tail = root;
el = root->level; while (tail->right) {
root); tail = tail->right;
}
q.empty()){
e *temp = q.front(); // Append the stored right subtree a
op(); it recursively
temp->level > level){ tail->right = rightSubtree;
cout<<endl; flatten(root->right); // here inste
level++; there can be a subtree and we need to flatte
}
t<<temp->key<<" "; };
temp->left != NULL) {
temp->left->level = temp->level + 1; AT THE END LEFT THERE COULD BE RIGHT SUBTREE
q.push(temp->left); HIGHER HEIGHT.So we flatten right subtree at

temp->right != NULL) { i
temp->right->level = temp->level + 1; 1
q.push(temp->right); / \
2 5
/ \
3 4

ii
1
levelwise elements \
); 2
pty()){ \
q.size(); 3
level_elements; \
level_size) { get front ,push it in 4
nts ,push it's children ,pop it } iii
1
\
2
y'to bst. \
elper(int l, int r, vector<int>& nums) { 3
(l > r) return nullptr; \
mid = (l + r) / 2; 4
eNode* root = new TreeNode(nums[mid]); \
t->left = helper(l, mid - 1, nums); 5
t->right = helper(mid + 1, r, nums);
urn root;

124. Binary Tree Maximum Path Sum.Path can b


1st child that we can see at each depth from the and end at any connecting points.
single left child then take that. as connecting root ust be included.
hy we maintained that depth So only 1 number can
ch depth. class Solution {
ion { public:
int path(int &maxi,TreeNode* root){
int> rightSideView(TreeNode* root) { if(!root)
tor<int> result; return 0;
htView(root, 0, result); int l=max(path(maxi,root->left),0);
urn result; int r=max(path(maxi,root->right),0);
maxi=max(maxi,l+r+root->val);//keep
if current node,l,r is a complete path then
maximum sum.
ghtView(TreeNode* node, int depth, vector<int>& return root->val+max(l,r); // we ar
only one of l,r because if we take both then
(!node) return; would be a complete path but the solution ha
(depth == result.size()) { complete path .
result.push_back(node->val); }
int maxPathSum(TreeNode* root) {
(node->right) { int maxi=INT_MIN;
rightView(node->right, depth + 1, result); path(maxi,root);
return maxi;
(node->left) { }
rightView(node->left, depth + 1, result); };

int> rightView(TreeNode* root) {


tor<int> result;
(!root) return result; #### Given two integer arrays preorder and i
where preorder is the preorder traversal of
ue<TreeNode*> q; tree and inorder is the inorder
ush(root); traversal of the same tree.Now prepare level
traversal.
le (!q.empty()) {
int levelSize = q.size();
In preorder there is root ,[root of left
// Traverse all nodes at the current level subtree,remaining of the left subtree],[root
for (int i = 0; i < levelSize; i++) { subtree ,remaining of right subtree].
TreeNode* node = q.front();
q.pop();
Inorder left subtree,root,right subtree.
// Capture the first element of each level for
If we go serially in preorder we will get ro
if (i == levelSize - 1) { level order.And if we search that root index
result.push_back(node->val); inorder then we will be able to
} get the elements of left subtree and right s

// Add child nodes to the queue


if (node->left) q.push(node->left); class Solution {
if (node->right) q.push(node->right); public:
} TreeNode* constructTree(vector < int > & pre
preStart, int preEnd, vector
< int > & inorder, int inStart, int inEnd,
urn result; int > & mp) {
if (preStart > preEnd || inStart > inEnd)
NULL;

TreeNode* root = new TreeNode(preorder[pre


int elem = mp[root -> val];
int nElem = elem - inStart;
"0","0","0"],
"0","0","0"], root -> left = constructTree(preorder, pre
"1","0","0"], preStart + nElem, inorder,
"0","1","1"] inStart, elem - 1, mp); //karon ekta range
element thakle oi 3 ta same subtree er but o
aversing from the top-left corner. We find the first alada preorder er inorder er.
tion (0,0). Then, we explore all its adjacent land //So amra nelem paoa mane root shoho oi su
size jana.So prestart+nelem use hoise.
izontally or vertically). So, we'll explore (0,1) root -> right = constructTree(preorder, pr
both of which are '1's. Then, we'll explore (1,1), nElem + 1, preEnd, inorder,
elem + 1, inEnd, mp);
nt, we've explored all connected land cells, and we
s the first island. return root; //after preparing root and it
left ,right child it's returned.
d to find the next unexplored '1' that can }
belong to another island. We continue traversing
w by row. So, we move to position (2,2), which is a TreeNode* buildTree(vector < int > & preorde
rt exploring from there. This becomes the second < int > & inorder) {
int preStart = 0, preEnd = preorder.size()
int inStart = 0, inEnd = inorder.size() -
we explore further and find the next island, which
the '1's at positions (3,3) and (3,4). map < int, int > mp;
ion { for (int i = inStart; i <= inEnd; i++) {
mp[inorder[i]] = i;
; }
Islands(vector<vector<char>>& grid) {
(grid.empty() || grid[0].empty()) return 0; return constructTree(preorder, preStart, p
inorder, inStart, inEnd, mp);
grid.size(); }
grid[0].size(); };
numIslands = 0;

(int i = 0; i < m; ++i) { // preStart + 1 to preStart + leftSubtreeSiz


for (int j = 0; j < n; ++j) { the number of elements results in leftSubtre
if (grid[i][j] == '1') { That's why range is like that.
++numIslands; // postorderStart, postorderStart + leftSubt
dfs(grid, i, j); 1 because the number of elements results in
} leftSubtreeSize too. ......
}

urn numIslands;

class Solution {
s[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; public:
TreeNode* buildTree(vector<int>& inorder
s(vector<vector<char>>& grid, int i, int j) { vector<int>& postorder) {
unordered_map<int, int> index;
d[i][j] = '0'; //dfs approch. Marking visited at the for (int i = 0; i < inorder.size();
e will also take out it's children and shove it in index[inorder[i]] = i;
lls }
return buildTreeHelper(inorder, post
(auto dir : dirs) { inorder.size() - 1, 0, postorder.size() - 1,
int x = i + dir[0]; }
int y = j + dir[1];
TreeNode* buildTreeHelper(vector<int>& i
if (x >= 0 && y >= 0 && x < m && y < n && grid[x] vector<int>& postorder, int inorderStart, in
{ inorderEnd, int postorderStart, int postorde
unordered_map<int, int>& index) {
dfs(grid, x, y); if (inorderStart > inorderEnd ||
} postorderStart > postorderEnd) {
return nullptr;
}
int rootVal = postorder[postorderEnd
TreeNode* root = new TreeNode(rootVa
int inorderRootIndex = index[rootVal
int leftSubtreeSize = inorderRootInd
inorderStart;
ree check. root->left = buildTreeHelper(inorder
ion { postorder, inorderStart, inorderRootIndex -
postorderStart, postorderStart + leftSubtree
Symmetric(TreeNode* root) { index);
(!root) return true; // An empty tree is symmetric root->right = buildTreeHelper(inorde
on postorder, inorderRootIndex + 1, inorderEnd,
postorderStart + leftSubtreeSize, postorderE
ue<TreeNode*> q; index);
ush(root); return root;
}
le (!q.empty()) { };
int levelSize = q.size();
vector<int> levelElements; postorder : left ,right,root.So we have
postorderStart, postorderStart + leftSubtree
for (int i = 0; i < levelSize; ++i) { left and rest is right.
TreeNode* curr = q.front();
q.pop();

if (curr) {
levelElements.push_back(curr->val);
q.push(curr->left); Given an m x n matrix board containing 'X' a
q.push(curr->right); capture all regions that are 4-directionally
} else { surrounded by 'X'.
levelElements.push_back(INT_MIN); //
for null nodes
} A region is captured by flipping all 'O's in
} that surrounded region.

// Check if the level elements are symmetric


if (!isSymmetricLevel(levelElements)) {
return false; Example 1:
}

Input:
urn true; board = [
["X","X","X","X"],
["X","O","O","X"],
SymmetricLevel(const vector<int>& levelElements) { ["X","X","O","X"],
n = levelElements.size(); ["X","O","X","X"]]
(int i = 0; i < n / 2; ++i) {
if (levelElements[i] != levelElements[n - 1 - i]) { Output: [
return false; ["X","X","X","X"],
} ["X","X","X","X"],
["X","X","X","X"],
urn true; ["X","O","X","X"]]

Explanation: Notice that an 'O' should not b


if:
x n integers matrix, return the length of the - It is on the border, or
reasing path in matrix. - It is adjacent to an 'O' that should not b
The bottom 'O' is on the border, so it is no
ell, you can either move in four directions: left, The other three 'O' form a surrounded region
or down. You may not move diagonally or are flipped.
de the boundary (i.e., wrap-around is not allowed). Example 2:

Input: board = [["X"]]


ix = [[9,9,4],[6,6,8],[2,1,1]] Output: [["X"]]

: The longest increasing path is [1, 2, 6, 9]. class Solution {


public:
void DFS(vector<vector<char>>& board, in
ix = [[3,4,5],[3,2,6],[2,2,1]] j, int m, int n) {
if(i<0 or j<0 or i>=m or j>=n or boa
: The longest increasing path is [3, 4, 5, 6].
onally is not allowed. = 'O') return;
board[i][j] = '#';
DFS(board, i-1, j, m, n);
ix = [[1]] DFS(board, i+1, j, m, n);
DFS(board, i, j-1, m, n);
DFS(board, i, j+1, m, n);
}

ion { void solve(vector<vector<char>>& board)

;
s[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}}; int m = board.size();

gestIncreasingPath(vector<vector<int>>& matrix) { if(m == 0) return;


(matrix.empty()) return 0;
int n = board[0].size();
= matrix.size();
= matrix[0].size(); //Moving over firts and last column
tor<vector<int>> memo(m, vector<int>(n, 0)); for(int i=0; i<m; i++) {
maxPath = 0; if(board[i][0] == 'O')
DFS(board, i, 0, m, n);
Loop through each cell in the matrix if(board[i][n-1] == 'O')
(int i = 0; i < m; ++i) { DFS(board, i, n-1, m, n);
for (int j = 0; j < n; ++j) { }
maxPath = max(maxPath, dfs(matrix, i, j,

} //Moving over first and last row


for(int j=0; j<n; j++) {
if(board[0][j] == 'O')
urn maxPath; DFS(board, 0, j, m, n);
if(board[m-1][j] == 'O')
DFS(board, m-1, j, m, n);
(vector<vector<int>>& matrix, int i, int j, }
or<int>>& memo) {
(memo[i][j] != 0) return memo[i][j]; for(int i=0; i<m; i++)
currPath = 1; for(int j=0; j<n; j++)
{
(auto dir : dirs) { if(board[i][j] == 'O')
int x = i + dir[0]; board[i][j] = 'X';
int y = j + dir[1]; if(board[i][j] == '#')
board[i][j] = 'O';
if (x >= 0 && x < m && y >= 0 && y < n && matrix[x] }
x[i][j]) { }
currPath = max(currPath, 1 + dfs(matrix, x, y, };

o[i][j] = currPath;
urn currPath;

You might also like