題目
翻轉(zhuǎn)一棵二叉樹扁瓢。
示例:
輸入:
4
/ \
2 7
/ \ / \
1 3 6 9
輸出:
4
/ \
7 2
/ \ / \
9 6 3 1
思路
思路簡單拴测,兩種方法忘朝,遞歸非遞歸
上代碼
代碼
//遞歸方式
def invertTree(self, root: TreeNode) -> TreeNode:
if root == None:
return root
temp = root.right
root.right = self.invertTree(root.left)
root.left = self.invertTree(temp)
return root
//非遞歸方式
def invertTree(self, root: TreeNode) -> TreeNode:
trees = []
trees.append(root)
while trees:
node = trees.pop()
if not node:
continue
tmp = node.left
node.left = node.right
node.right = tmp
trees.append(node.left)
trees.append(node.right)
return root
以上
歡迎大家關(guān)注我的公眾號