Complete the code to return the left child of a node.
TreeNode* leftChild = node->[1];The left child of a node in a BST is accessed using node->left.
Complete the code to find the minimum node in a BST subtree.
while (current->[1] != nullptr) { current = current->[1]; }
To find the minimum node in a BST subtree, keep moving to the left child until it is null.
Fix the error in the code to find the inorder successor when the node has no right child.
TreeNode* successor = nullptr; TreeNode* ancestor = root; while (ancestor != node) { if (node->val < ancestor->val) { successor = ancestor; ancestor = ancestor->[1]; } else { ancestor = ancestor->right; } }
When the node has no right child, move up the tree via ancestors. If node's value is less than ancestor's, go left.
Fill both blanks to complete the function that finds the inorder successor in a BST.
if (node->right != nullptr) { TreeNode* temp = node->right; while (temp->[1] != nullptr) { temp = temp->[2]; } return temp; }
The inorder successor in the right subtree is the leftmost node. So keep moving left.
Fill all three blanks to complete the full inorder successor function in a BST without parent pointers.
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* node) {
if (node->right != nullptr) {
TreeNode* temp = node->right;
while (temp->[1] != nullptr) {
temp = temp->[2];
}
return temp;
}
TreeNode* successor = nullptr;
TreeNode* ancestor = root;
while (ancestor != node) {
if (node->val < ancestor->val) {
successor = ancestor;
ancestor = ancestor->[3];
} else {
ancestor = ancestor->right;
}
}
return successor;
}First, find the leftmost node in the right subtree. If no right child, traverse from root to find the lowest ancestor whose left child is also ancestor of node.