請完成一個函數,輸入一個二叉樹,該函數輸出它的鏡像。
例如輸入:
4
/
2 7
/ \ /
1 3 6 9
鏡像輸出:
4
/
7 2
/ \ /
9 6 3 1
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/er-cha-shu-de-jing-xiang-lcof
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
這個題目比較簡單,思路就是依次遍歷二叉樹的各個節點並交換左右子樹。這裏複習一下遍歷二叉樹的三種思路:遞歸、棧(先序遍歷)、隊列(層次遍歷)
遞歸
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
root.left,root.right=self.mirrorTree(root.right),self.mirrorTree(root.left)
return root
輔助棧
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
s=[root]
while len(s):
t=s.pop()
if t.left:
s.append(t.left)
if t.right:
s.append(t.right)
t.left,t.right=t.right,t.left
return root
隊列
class Solution:
def mirrorTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
s=[root]
while len(s):
t=s.pop()
if t.left:
s.insert(0,t.left)
if t.right:
s.insert(0,t.right)
t.left,t.right=t.right,t.left
return root