新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
聊聊二叉樹的左右子樹交換
本文轉(zhuǎn)載自微信公眾號「三分鐘學前端」,作者sisterAn。轉(zhuǎn)載本文請聯(lián)系三分鐘學前端公眾號。

成都創(chuàng)新互聯(lián)專注于企業(yè)成都全網(wǎng)營銷、網(wǎng)站重做改版、惠濟網(wǎng)站定制設(shè)計、自適應(yīng)品牌網(wǎng)站建設(shè)、H5高端網(wǎng)站建設(shè)、商城網(wǎng)站定制開發(fā)、集團公司官網(wǎng)建設(shè)、外貿(mào)營銷網(wǎng)站建設(shè)、高端網(wǎng)站制作、響應(yīng)式網(wǎng)頁設(shè)計等建站業(yè)務(wù),價格優(yōu)惠性價比高,為惠濟等各大城市提供網(wǎng)站開發(fā)制作服務(wù)。
翻轉(zhuǎn)一棵二叉樹。
示例:
輸入:
- 4
- / \
- 2 7
- / \ / \
- 1 3 6 9
輸出:
- 4
- / \
- 7 2
- / \ / \
- 9 6 3 1
遍歷+交換左右子樹
解題思路: 從根節(jié)點開始依次遍歷每個節(jié)點,然后交換左右子樹既可
- const invertTree = (root) => {
- if(!root) return null
- // 先翻轉(zhuǎn)當前節(jié)點的左右子樹
- const temp = root.left
- root.left = root.right
- root.right = temp
- // 然后遍歷左子樹
- invertTree(root.left)
- // 再遍歷右子樹
- invertTree(root.right)
- return root
- }
這里采用的是前序遍歷,也可以是后序遍歷或?qū)有虮闅v
leetcode:https://leetcode-cn.com/problems/invert-binary-tree
本文名稱:聊聊二叉樹的左右子樹交換
標題URL:http://fisionsoft.com.cn/article/dpeojip.html


咨詢
建站咨詢
