11.6随笔

这里是11.6随笔。
题目留档:以二叉链表作为二叉树的存储结构,编写程序实现:交换二叉树每个结点的左子树和右子树。以先序遍历构建一棵二叉树,输出中序遍历结果,交换每个节点的左右子树后,输出中序遍历结果。
代码:#include

include

struct TreeNode {
char val;
TreeNode* left;
TreeNode* right;
TreeNode(char x) : val(x), left(NULL), right(NULL) {}
};

TreeNode* buildTree(std::string preorder, int& index) {
char ch = preorder[index];
if (ch == '#') {
index++;
return NULL;
}
TreeNode* root = new TreeNode(ch);
index++;
root->left = buildTree(preorder, index);
root->right = buildTree(preorder, index);
return root;
}

void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
std::cout << root->val;
inorderTraversal(root->right);
}

void swapTree(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* temp = root->left;
root->left = root->right;
root->right = temp;
swapTree(root->left);
swapTree(root->right);
}

int main() {
std::string preorder;
std::cin >> preorder;
int index = 0;
TreeNode* root = buildTree(preorder, index);

inorderTraversal(root);
std::cout << std::endl;

swapTree(root);
inorderTraversal(root);
std::cout << std::endl;


return 0;

}

posted @ 2024-11-06 20:46  Thanatos。syts  阅读(3)  评论(0编辑  收藏  举报