226. 翻转二叉树

题目

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

示例1:

示例1

输入:

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

示例2:

示例2

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

示例3:

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

提示:

  • 树中节点数目范围在 [0, 100]
  • -100 <= Node.val <= 100

解法

解法一:

递归

Java

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
private void exchange(TreeNode root){
TreeNode node = root;
if(node != null){
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
}

public TreeNode invertTree(TreeNode root) {
TreeNode node = root;

if(root == null) {
return root;
}

invertTree(node.left);
invertTree(node.right);
exchange(node);
return root;
}
}
0%