LeetCode226-翻转二叉树

LeetCode226-翻转二叉树

前序遍历翻转

1
2
3
4
5
6
7
8
9
10
11
12
13
//递归前序遍历进行交换
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
//交换左右结点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
invertTree(root.right);
return root;
}

中序遍历翻转

1
2
3
4
5
6
7
8
9
10
11
12
13
//递归中序遍历进行交换
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
invertTree(root.left);
//交换左右结点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
invertTree(root.left);
return root;
}

后序遍历翻转

1
2
3
4
5
6
7
8
9
10
11
12
13
//递归后序遍历进行交换
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
invertTree(root.left);
invertTree(root.right);
//交换左右结点
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
return root;
}

层序遍历翻转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//层序遍历进行翻转左右子树
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(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;
}