翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
第一种思路:
递归+交换左右子树+保留最初的树
代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
tmp0=root
tmp=root.right
root.right=root.left
root.left=tmp
self.invertTree(root.right)
self.invertTree(root.left)
return tmp0
第二种思路:迭代+深度优先,用广度优先搜索的方法来进行解题,将每一层的字数加入到stack中,然后对每一个子树的左右子树进行交换
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root : return
stack = [root]
while stack :
length = len(stack)
for i in range(length):
cur = stack.pop(0)
cur.left,cur.right = cur.right,cur.left
if cur.left :
stack.append(cur.left)
if cur.right :
stack.append(cur.right)
return root