今日新学了20个单词,复习32个。上午上了一节数据结构课学了些栈和队列,下午上了java课。出于竞赛知识需要,晚上学了些二叉树三种遍历方式的相关知识。以下是我用cpp完成的前序,中序,后序遍历二叉树的代码实现。
include
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root == nullptr) return;
std::cout << root->val << " ";
preorderTraversal(root->left);
preorderTraversal(root->right);
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root == nullptr) return;
inorderTraversal(root->left);
std::cout << root->val << " ";
inorderTraversal(root->right);
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root == nullptr) return;
postorderTraversal(root->left);
postorderTraversal(root->right);
std::cout << root->val << " ";
}
};
int main() {
// 构建二叉树
new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->right->right = new TreeNode(5);
Solution solution;
// 前序遍历
std::cout << "Preorder traversal: ";
solution.preorderTraversal(root);
std::cout << std::endl;
// 中序遍历
std::cout << "Inorder traversal: ";
solution.inorderTraversal(root);
std::cout << std::endl;
// 后序遍历
std::cout << "Postorder traversal: ";
solution.postorderTraversal(root);
std::cout << std::endl;
// 清理内存
delete root->left->left;
delete root->left;
delete root->right->right;
delete root->right;
delete root;
return 0;
}
标签:10,right,TreeNode,14,val,2024,遍历,root,left From: https://www.cnblogs.com/szxworld/p/18466381