首页 技术 正文
技术 2022年11月15日
0 收藏 323 点赞 5,260 浏览 1359 个字

226. 翻转二叉树

翻转一棵二叉树。

示例:

输入:

     4
/ \
2 7
/ \ / \
1 3 6 9

输出:

     4
/ \
7 2
/ \ / \
9 6 3 1

备注:

这个问题是受到 Max Howell 的 原问题 启发的 :

谷歌:我们90%的工程师使用您编写的软件(Homebrew),但是您却无法在面试时在白板上写出翻转二叉树这道题,这太糟糕了。

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
// 先序遍历--从顶向下交换
// public TreeNode invertTree(TreeNode root) {
// if (root == null) return null;
// // 保存右子树
// TreeNode rightTree = root.right;
// // 交换左右子树的位置
// root.right = invertTree(root.left);
// root.left = invertTree(rightTree);
// return root;
// }//中序遍历
// public TreeNode invertTree(TreeNode root) {
// if (root == null) return null;
// invertTree(root.left); // 递归找到左节点
// TreeNode rightNode= root.right; // 保存右节点
// root.right = root.left;
// root.left = rightNode;
// // 递归找到右节点 继续交换 : 因为此时左右节点已经交换了,所以此时的右节点为root.left
// invertTree(root.left);
// }//后序遍历
// public TreeNode invertTree(TreeNode root) {
// // 后序遍历-- 从下向上交换
// if (root == null) return null;
// TreeNode leftNode = invertTree(root.left);
// TreeNode rightNode = invertTree(root.right);
// root.right = leftNode;
// root.left = rightNode;
// return root;
// }//层次遍历
public TreeNode invertTree(TreeNode root) {
// 层次遍历--直接左右交换即可
if (root == null) return null;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
TreeNode node = queue.poll();
TreeNode rightTree = node.right;
node.right = node.left;
node.left = rightTree;
if (node.left != null){
queue.offer(node.left);
}
if (node.right != null){
queue.offer(node.right);
}
}
return root;
}}
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295