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;
}
}

最新文章

  1. GitHub管理代码-随笔
  2. gcc命令中参数c和o混合使用的详解[转载]
  3. Redis的介绍及使用实例.
  4. php中关于抽象(abstract)类和抽象方法的问题解析
  5. 自动化测试平台CATP
  6. SanDisk SecureAccess™ Software
  7. window远程连接linux
  8. 刚接触js不久,自己写的banner幻灯片效果。
  9. handler更新UI主线程
  10. C#设计模式之二十二备忘录模式(Memento Pattern)【行为型】
  11. 多媒体开发(6):滤镜实现各种图片效果 | Video-Filters | avfilter | 变色
  12. 「JLOI2015」战争调度 解题报告
  13. docker挂载点泄露问题
  14. Dubbo接口压测
  15. Module(模块)
  16. linux kernel notifier chain(事件通知链)
  17. 安装python3后使用pip和pip3的区别是什么?
  18. Azure 虚拟机代理概述
  19. MySQL基础值 存储过程和函数
  20. C++ 著名程序库 概览

热门文章

  1. 前端基础之css样式(选择器)
  2. JAVA虚拟机(JVM)以及跨平台原理(JDK、JRE、JVM)
  3. UI控件之UINavigationController
  4. centos6 没有eth0网络
  5. 【Tech】CAS RESTful API使用笔记
  6. 数据库自动增长id下一次的值
  7. NAS、SAN、DAS 说明
  8. 20145231 《Java程序设计》第一周学习总结
  9. Java基础面试集合
  10. java基础之final/static/static final