翻转二叉树

leetCode–226(翻转二叉树)

给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。

示例 1:

image-20220608164849018

1
2
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]

示例 2:

image-20220608164859662

1
2
输入:root = [2,1,3]
输出:[2,3,1]

示例 3:

1
2
输入:root = []
输出:[]

解法一:递归

遍历每个节点,转换每个节点的左右子树。这个想法要是想到了,代码会很简单,但没想到!

代码为:

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root==null) return null;
//左右子树进行交换
TreeNode t = root.left;
root.left = root.right;
root.right = t;
//遍历左节点,让左节点的左右子树交换
if (root.left!=null) invertTree(root.left);
//遍历右节点,让右节点的左右子树交换
if (root.right!=null) invertTree(root.right);
return root;
}
}

解法二:迭代

额外的数据结构–队列,来存放临时遍历到的元素。

代码为:

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
34
35
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
//迭代
public TreeNode invertTree(TreeNode root) {
if (root==null) return null;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()){
//每次从队列中拿出一个节点,并交换左右子树
TreeNode a = stack.pop();
TreeNode t = a.left;
a.left = a.right;
a.right = t;
//如果当前节点的左子树不为空,则放入队列等待后续处理
if (a.left!=null) stack.push(a.left);
//如果当前节点的右子树不为空,则放入队列等待后续处理
if (a.right!=null) stack.push(a.right);
}
return root;
}
}

翻转二叉树
http://example.com/2022/06/08/翻转二叉树/
作者
zlw
发布于
2022年6月8日
许可协议