- Invert Binary Tree:题目链接
DFS-递归
1 | class Solution { |
BFS-层次遍历
在层次遍历出队时,将队首结点的左右孩子互换1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25class Solution {
// BFS 时间复杂度O(N) 空间复杂度O(M)M:队列的长度
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode front = queue.poll();
// 在将队首结点出队的时候 将队首结点的左右孩子 互换
TreeNode temp = front.left;
front.left = front.right;
front.right = temp;
if (front.left != null) {
queue.offer(front.left);
}
if (front.right != null) {
queue.offer(front.right);
}
}
return root;
}
}