剑指Offer 1521 二叉树的镜像
来源:互联网 发布:路由器mac地址 编辑:程序博客网 时间:2024/05/18 00:19
第15题:
题目:输入一颗二元查找树,将该树转换为它的镜像,
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
#include <cstdlib>#include <iostream>#include <stdio.h>using namespace std;struct TreeNode{ TreeNode *left; TreeNode *right; int value;};bool firstprint;void change(TreeNode *current){ if(current->left == NULL && current->right == NULL) return; if(current->left != NULL) change(current->left); if(current->right != NULL) change(current->right); if(current->left != NULL || current->right != NULL) { TreeNode *temp = current->left; current->left = current->right; current->right = temp; }}/*void change(TreeNode *root){ if(root==NULL) { return; } TreeNode *temp = root->left; root->left = root->right; root->right = temp; if(root->left) change(root->left); if(root->right) change(root->right);}*/void preTravel(TreeNode *current){ if(current){ if(firstprint == true) { printf("%d",current->value); firstprint = false ; } else printf(" %d",current->value); preTravel(current->left); preTravel(current->right); }}int main(int argc, char *argv[]){ TreeNode node[1500]; int n; int one, two; char ci; while(scanf("%d", &n) != EOF) { firstprint = true; for(int i = 0; i < n; i++) cin >> node[i].value; for(int i = 0; i < n; i++) { cin >> ci; if(ci == 'd') { cin >> one >> two; node[i].left = &node[one-1]; node[i].right = &node[two-1]; } else if(ci == 'l') { cin >> one; node[i].left = &node[one-1]; node[i].right = NULL; } else if(ci == 'r') { cin >> two; node[i].left = NULL; node[i].right = &node[two-1]; } else { node[i].left = NULL; node[i].right = NULL; } } if(n == 0) printf("NULL\n"); else { change(&node[0]); preTravel(&node[0]); printf("\n"); } } return 0;}
- 【剑指offer】二叉树的镜像
- [剑指Offer]二叉树的镜像
- 剑指offer--二叉树的镜像
- 剑指Offer-二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指 offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指offer 二叉树的镜像
- [剑指offer]二叉树的镜像
- 《剑指offer》-二叉树的镜像
- 剑指Offer:二叉树的镜像
- 剑指offer|二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指Offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指Offer:二叉树的镜像
- 剑指offer-二叉树的镜像
- 剑指offer 二叉树的镜像
- 大数据核心技术源码分析之-Avro篇-2
- [week2]每周总结与工作计划
- 谈谈对攻读计算机研究生的看法
- 关系数据库的特点
- Mysql 创建用户、删除用户
- 剑指Offer 1521 二叉树的镜像
- 杭州赛区网络赛
- Exception in thread "main" java.lang.NoClassDefFoundError: org.jaxen.NamespaceContext
- 东方故事的故事大概
- Java面试题之一
- 怎样在ubuntu下写c++程序
- 图片,70后,你懂的
- fvwm使用 2
- xml中xPath的使用