LeetCode 之 JavaScript 解答第226题 —— 翻转二叉树(Invert Binary Tree)
栏目: JavaScript · 发布时间: 6年前
内容简介:Time:2019/4/21Title: Invert Binary TreeDifficulty: Easy
Time:2019/4/21
Title: Invert Binary Tree
Difficulty: Easy
Author: 小鹿
题目:Invert Binary Tree(反转二叉树)
Invert a binary tree.
反转二叉树
Example:
Input:
4 / \ 2 7 / \ / \ 1 3 6 9
Output:
4 / \ 7 2 / \ / \ 9 6 3 1
Solve:
▉ 问题分析
由上图可以分析反转二叉树,只是对左右子树的数据进行交换,再仔细观察,并不是每个节点的左右子树进行交换,而是左子树的叶子节点和右子树的叶子节点进行交换,另外两个子节点进行交换,那我们不得不用到递归了。
▉ 算法思路
2)左右子树结点交换。 3)分别对左右子树进行递归。
▉ 代码实现
var invertTree = function(root) { //判断当前树是否为 null if(root == null) return root; //左右子树结点交换 let right = root.right; let left = root.left; root.right = left; root.left = right; //分别对左右子树进行递归 invertTree(left); invertTree(right); //返回树的根节点 return root; };
欢迎一起加入到 LeetCode 开源 Github 仓库,可以向 me 提交您其他语言的代码。在仓库上坚持和小伙伴们一起打卡,共同完善我们的开源小仓库!
Github: https://github.com/luxiangqia...
欢迎关注我个人公众号:「一个不甘平凡的码农」,记录了自己一路自学编程的故事。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- canvas 图像旋转与翻转姿势解锁
- CSS3实现卡片翻转动画效果
- canvas 图像旋转与翻转姿势解锁
- 图解:K 个一组翻转链表
- leetcode 25. k个一组翻转链表
- 简单几步,用纯CSS3实现3D翻转效果!
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
We Are the Nerds
Christine Lagorio-Chafkin / Hachette Books / 2018-10-2 / USD 18.30
Reddit hails itself as "the front page of the Internet." It's the third most-visited website in the United States--and yet, millions of Americans have no idea what it is. We Are the Nerds is an eng......一起来看看 《We Are the Nerds》 这本书的介绍吧!
SHA 加密
SHA 加密工具
RGB HSV 转换
RGB HSV 互转工具