剑指offer(18)—二叉树的镜像
来源:互联网 发布:卡尔波普尔 知乎 编辑:程序博客网 时间:2024/06/05 05:10
二叉树的镜像
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5
思路
递归 or 非递归
代码
递归
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution {public: void Mirror(TreeNode *pRoot) { if(pRoot == NULL) return; //交换左右子结点 TreeNode* ptmp; ptmp = pRoot->left; pRoot->left = pRoot->right; pRoot->right = ptmp; Mirror(pRoot->left); //对左子树进行镜像操作 Mirror(pRoot->right); //对右子树进行镜像操作 return; }};
非递归
/*struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { }};*/class Solution {public: void Mirror(TreeNode *pRoot) { //栈的非递归 if(pRoot == NULL) return; stack<TreeNode *> st; st.push(pRoot); TreeNode *ptmp, *ptop; while(st.size() > 0){ ptop = st.top(); st.pop(); ptmp = ptop->left; ptop->left = ptop->right; ptop->right = ptmp; if(ptop->left) st.push(ptop->left); if(ptop->right) st.push(ptop->right); } return; }};
阅读全文
0 0
- 剑指Offer—18—二叉树的镜像
- 剑指offer(18)—二叉树的镜像
- 【剑指offer】二叉树的镜像
- [剑指Offer]二叉树的镜像
- 剑指offer--二叉树的镜像
- 剑指Offer-二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指 offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指offer 二叉树的镜像
- [剑指offer]二叉树的镜像
- 《剑指offer》-二叉树的镜像
- 剑指Offer:二叉树的镜像
- 剑指offer|二叉树的镜像
- 《剑指offer》二叉树的镜像
- 剑指Offer:二叉树的镜像
- 【剑指offer】二叉树的镜像
- 剑指Offer:二叉树的镜像
- Raft一致性算法
- 文本处理工具sed
- 七夕告白
- 最多有多少个点在一条直线上-LintCode
- 在CentOS搭建Git服务器
- 剑指offer(18)—二叉树的镜像
- 微服务所用到的各类工具和包
- intellij idea环境android apk性能分析
- 【转】JAVA内存泄露分析及解决
- 微型四轴飞行器(5)九轴姿态融合算法B
- 如何在NAS中破解Resilio Sync同步软件
- python 实现多线程编程
- Git Push 错误 [remote rejected] master -> master (branch is currently checked out) & 无法查看push后的git中文件(
- 更新java表格数据时使用json回显数据失败的解决办法