翻转二叉树
来源:互联网 发布:女朋友胸很大知乎 编辑:程序博客网 时间:2024/05/29 17:18
问题描述:
翻转一棵二叉树
样例
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
TreeNode *temp;
if(root==NULL) return;
else{
temp=root->left;
root->left=root->right;
root->right=temp;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
}
};
解题感想:
temp的使用,root==NULL时,直接返回。
- C++二叉树翻转
- 翻转二叉树
- 翻转二叉树
- 题目:翻转二叉树
- LintCode 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode_175_翻转二叉树
- 二叉树翻转
- lintcode ----翻转二叉树
- lintcode,翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- LintCode-翻转二叉树
- SubscriptionInfo框架分析
- 链接对象links
- [常用]按back键退出实现“再按一次退出”的功能两中方式
- 初学PHP
- all数组
- 翻转二叉树
- 判断回文
- Spring学习-20:Spring的AOP:自动代理
- 【python学习笔记】2:收集最多价值奖品问题
- bootstrap-table的toolbar用法自定义增删改查工具容器
- anchors数组
- 链表基础之翻转,删除
- 表单基础
- 框架的创建