博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Invert Binary Tree
阅读量:7062 次
发布时间:2019-06-28

本文共 1485 字,大约阅读时间需要 4 分钟。

After reading the quote below the problem, you will be motivated to solve it immediately :-) Well, indeed it is also relative easy. The process of inverting a binary tree is simply 3 steps:

  1. Swap the left subtree and the right subtree;
  2. Invert the left subtree;
  3. Invert the right subtree.

So we immediately have the following simple recursive solution.

1 class Solution { 2 public: 3     TreeNode* invertTree(TreeNode* root) { 4         if (!root) return NULL; 5         swap(root -> left, root -> right); 6         root -> left = invertTree(root -> left); 7         root -> right = invertTree(root -> right); 8         return root; 9     }10 };

Well, you may also want to challenge yourself to solve it iteratively. The iterative solution is basically a level-order traversal. Push all the nodes of the same level to a queue and then swap their left subtree and right subtree and iterate over their subtrees.

The code is as follows.

1 class Solution { 2 public: 3     TreeNode* invertTree(TreeNode* root) { 4         if (!root) return NULL; 5         queue
level; 6 level.push(root); 7 while (!level.empty()) { 8 TreeNode* node = level.front(); 9 level.pop();10 swap(node -> left, node -> right);11 if (node -> left) level.push(node -> left);12 if (node -> right) level.push(node -> right);13 }14 return root; 15 }16 };

 

转载于:https://www.cnblogs.com/jcliBlogger/p/4572106.html

你可能感兴趣的文章
博文收藏夹
查看>>
kibana5.6源码分析2
查看>>
strcpy、strcat、strstr的实现
查看>>
MySQL Timeout解析
查看>>
SpringMVC04controller中定义多个方法
查看>>
Ext.Net GridPanel属性配置
查看>>
hdfoo站点开发笔记-2
查看>>
tp剩余未验证内容-2
查看>>
Java反射在JVM的实现
查看>>
Java 存储时间戳的几种方式
查看>>
margin:0 auto
查看>>
case when
查看>>
[转载] HTML简介
查看>>
Oracle 查看表空间的大小及使用情况sql语句
查看>>
Android画图并保存图片(转载)
查看>>
移动下标效果
查看>>
eclipse 性能调优之内存分配
查看>>
c语言程序开发过程,编译的完整过程
查看>>
POJ2472106 miles to Chicago
查看>>
python高级(4)—— 虚拟环境安装使用
查看>>