聊聊二叉樹的左右子樹交換
作者: sisterAn
二叉樹(Binary tree)是樹形結構的一個重要類型。許多實際問題抽象出來的數據結構往往是二叉樹形式,即使是一般的樹也能簡單地轉換為二叉樹,而且二叉樹的存儲結構及其算法都較為簡單,因此二叉樹顯得特別重要。
本文轉載自微信公眾號「三分鐘學前端」,作者sisterAn。轉載本文請聯系三分鐘學前端公眾號。
翻轉一棵二叉樹。
示例:
輸入:
- 4
- / \
- 2 7
- / \ / \
- 1 3 6 9
輸出:
- 4
- / \
- 7 2
- / \ / \
- 9 6 3 1
遍歷+交換左右子樹
解題思路: 從根節點開始依次遍歷每個節點,然后交換左右子樹既可
- const invertTree = (root) => {
- if(!root) return null
- // 先翻轉當前節點的左右子樹
- const temp = root.left
- root.left = root.right
- root.right = temp
- // 然后遍歷左子樹
- invertTree(root.left)
- // 再遍歷右子樹
- invertTree(root.right)
- return root
- }
這里采用的是前序遍歷,也可以是后序遍歷或層序遍歷
leetcode:https://leetcode-cn.com/problems/invert-binary-tree
責任編輯:武曉燕
來源:
三分鐘學前端