LeetCode 226.翻转二叉树/《剑指Offer》27.二叉树的镜像

翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

输出:

1
2
3
4
5
     4
/ \
7 2
/ \ / \
9 6 3 1

方法一:递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 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
node = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(node)
return root

复杂度分析:时间复杂度和空间复杂度均为O(n)。

方法二:迭代(深度优先)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# 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;
stack = [root]
while stack:
node = stack.pop()

temp = node.left
node.left = node.right
node.right = temp

if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root

复杂度分析:时间复杂度和空间复杂度均为O(n)。

方法三:迭代(广度优先)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root == null) {
return root;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
TreeNode node = queue.poll();

TreeNode temp = node.left;
node.left = node.right;
node.right = temp;

if(node.left != null) {
queue.offer(node.left);
}
if(node.right != null) {
queue.offer(node.right);
}
}
return root;
}
}

复杂度分析:时间复杂度和空间复杂度均为O(n)。


----------本文结束感谢您的阅读----------
坚持原创技术分享,您的支持将鼓励我继续创作!