題目
難度:★☆☆☆☆
類(lèi)型:二叉樹(shù)
翻轉(zhuǎn)一棵二叉樹(shù)。
示例
輸入:
4
/ \
2 7
/ \ / \
1 3 6 9
輸出:
4
/ \
7 2
/ \ / \
9 6 3 1
解答
樹(shù)的問(wèn)題我們一般通過(guò)遞歸實(shí)現(xiàn)。翻轉(zhuǎn)一棵樹(shù),需要進(jìn)行以下步驟:
如果樹(shù)為空,則直接返回這棵樹(shù);
交換根節(jié)點(diǎn)的左右子樹(shù);
對(duì)樹(shù)的左右子樹(shù)分別進(jìn)行翻轉(zhuǎn),通過(guò)遞歸調(diào)用本函數(shù)實(shí)現(xiàn)。
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root: # 如果輸入不為空樹(shù)
root.left, root.right = root.right, root.left # 左右子樹(shù)互換
self.invertTree(root.left) # 翻轉(zhuǎn)左子樹(shù)
self.invertTree(root.right) # 翻轉(zhuǎn)右子樹(shù)
return root # 返回翻轉(zhuǎn)結(jié)束的二叉樹(shù)的根結(jié)點(diǎn)
如有疑問(wèn)或建議,歡迎評(píng)論區(qū)留言~