今日新學了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;
}