LintCode 翻转二叉树
来源:互联网 发布:sql server 2005 教程 编辑:程序博客网 时间:2024/06/05 02:23
1.描述
翻转一棵二叉树
样例
1 1 / \ / \2 3 => 3 2 / \ 4 4
2.分析
翻转一个二叉树使所有节点的左右孩子都交换,若只有一个节点即使当前节点的左孩子变为右孩子,
右孩子变为左孩子。整个二叉树的翻转即对根节点做翻转操作后将做操作的节点变为根节点的左右孩子。
这就是一个很典型的递归操作,一个节点的翻转,之后每个节点都是如此。
3.代码
/**
* 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
TreeNode *temp;
if(root==NULL) return;
else
{
temp=root->left;//将左右孩子互换
root->left=root->right;
root->right=temp;
invertBinaryTree(root->left);//做操作的节点向下移,最终完成对每一个节点的翻转操作
invertBinaryTree(root->right);
}
}
};
* 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
TreeNode *temp;
if(root==NULL) return;
else
{
temp=root->left;//将左右孩子互换
root->left=root->right;
root->right=temp;
invertBinaryTree(root->left);//做操作的节点向下移,最终完成对每一个节点的翻转操作
invertBinaryTree(root->right);
}
}
};
4.总结
使一个节点的左右孩子互换并不是让他们的值交换,而是让本来指向左孩子的指针
指向右孩子,指向右孩子的指针指向左孩子。
0 0
- LintCode 翻转二叉树
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- LintCode-翻转二叉树
- LintCode 翻转二叉树
- 翻转二叉树-LintCode
- lintcode 翻转二叉树
- LintCode 翻转二叉树
- 翻转二叉树-LintCode
- lintcode翻转二叉树
- LintCode - 175.翻转二叉树
- lintcode 175 翻转二叉树
- [LintCode]175.翻转二叉树
- [Lintcode] #175 翻转二叉树
- 二叉树专题-lintcode翻转二叉树
- LintCode --invert-binary-tree(翻转二叉树)
- LintCode--翻转二叉树(非递归)
- lintcode——翻转二叉树
- 图形
- POJ 1013 Counterfeit Dollar 笔记 模拟
- 详解网页中的瀑布流显示效果
- 这是一个基于Vue2实现的网易云音乐MV的webapp。
- Django数据库操作中You are trying to add a non-nullable field 'name' to contact without a default错误处理
- LintCode 翻转二叉树
- R语言矢量数据空间分析一:入门及rgeo包简介
- 关于C++类(一)
- hive合并小文件
- 如何查看Linux下面某一个目录下所有的隐藏文件和文件夹
- 递归(recursion)
- KMP模式串匹配模板
- linux tcp三路握手详解
- ubuntu下apache配置https且强制http转向为https