#include <queue>
void levelOrder(TreeNode* root) {
if (!root) return;
std::queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* cur = q.front(); q.pop();
std::cout << cur->val << " ";
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
}
五、常见算法题示例(C++)
1. 判断是否为合法 BST
cpp复制代码
bool isValidBST(TreeNode* root, TreeNode* min = nullptr, TreeNode* max = nullptr) {
if (!root) return true;
if ((min && root->val <= min->val) || (max && root->val >= max->val)) return false;
return isValidBST(root->left, min, root) && isValidBST(root->right, root, max);
}
2. 二叉树最大深度
cpp复制代码
int maxDepth(TreeNode* root) {
if (!root) return 0;
return 1 + std::max(maxDepth(root->left), maxDepth(root->right));
}
3. 路径总和是否等于 target
cpp复制代码
bool hasPathSum(TreeNode* root, int sum) {
if (!root) return false;
if (!root->left && !root->right) return sum == root->val;
return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val);
}
六、二叉搜索树(BST)操作实现
插入节点
cpp复制代码
TreeNode* insert(TreeNode* root, int val) {
if (!root) return new TreeNode(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
查找最小值
cpp复制代码
int findMin(TreeNode* root) {
while (root->left) root = root->left;
return root->val;
}