翻转二叉树
来源:互联网 发布:为什么淘宝没有电棒 编辑:程序博客网 时间:2024/06/03 23:02
一.题目描述
翻转一棵二叉树
样例
1 1 / \ / \2 3 => 3 2 / \ 4 4
二.解题思路
令根节点的左子树等于右子树,右子树等于左子树,利用递归的方法将每一个节点的左右子树翻转,从而完成整个树的翻转.
三.实现代码
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
if(root==NULL) return;
TreeNode *f=new TreeNode;
f=root->left;
root->left=root->right;
root->right=f;
invertBinaryTree(root->right);
invertBinaryTree(root->left);
}
};
四.感悟
在将根节点的左右子树翻转的时候要注意申请一个新的节点用来保存左子树.
0 0
- C++二叉树翻转
- 翻转二叉树
- 翻转二叉树
- 题目:翻转二叉树
- LintCode 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode_175_翻转二叉树
- 二叉树翻转
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode-翻转二叉树
- python保存和加载numpy数组
- 查找python第三方包各个版本的方法
- Android动画之ViewAnimation(TweenAnimation)视图动画(补间动画)
- 数组
- apache集成weblogic,Cannot open TEMP post file问题
- 翻转二叉树
- Hadoop MapReduce 在某一列上自连接(self join)
- [JZOJ5073]【GDOI2017第三轮模拟day1】影魔
- Neural Module Networks
- 配置伪分布式时的问题”JAVA_HOME is not set and could not be found“解决方法
- redis.conf 常用配置文件详解
- 数据库基础知识7
- 题目1154:Jungle Roads
- 欢迎使用CSDN-markdown编辑器