LeetCode OJ:Invert Binary Tree(反转二叉树)
2024-10-17 05:39:16
Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.
反转二叉树,递归的执行反转就行了:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return NULL;
swap(root->left, root->right);
root->left = invertTree(root->left);
root->right = invertTree(root->right);
return root;
}
};
java版本的如下所示(由于不方便使用swap,所以这里采取的另一种的方式):
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null)
return root;
TreeNode leftNew = invertTree(root.right);
TreeNode rightNew = invertTree(root.left);
root.left = leftNew;
root.right = rightNew;
return root;
}
}
最新文章
- GitHub管理代码-随笔
- gcc命令中参数c和o混合使用的详解[转载]
- Redis的介绍及使用实例.
- php中关于抽象(abstract)类和抽象方法的问题解析
- 自动化测试平台CATP
- SanDisk SecureAccess™ Software
- window远程连接linux
- 刚接触js不久,自己写的banner幻灯片效果。
- handler更新UI主线程
- C#设计模式之二十二备忘录模式(Memento Pattern)【行为型】
- 多媒体开发(6):滤镜实现各种图片效果 | Video-Filters | avfilter | 变色
- 「JLOI2015」战争调度 解题报告
- docker挂载点泄露问题
- Dubbo接口压测
- Module(模块)
- linux kernel notifier chain(事件通知链)
- 安装python3后使用pip和pip3的区别是什么?
- Azure 虚拟机代理概述
- MySQL基础值 存储过程和函数
- C++ 著名程序库 概览