226. 翻转二叉树
# 226. 翻转二叉树 (opens new window)
解题思路:递归,每次遍历时交换左右子树位置。
class Solution {
public TreeNode invertTree(TreeNode root) {
return dfs(root);
}
public TreeNode dfs(TreeNode root){
if(root==null) return null;
if(root.right==null&&root.left==null){
return root;
}
TreeNode leftchild=dfs(root.left);
TreeNode rightchild=dfs(root.right);
root.left=rightchild;
root.right=leftchild;
return root;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
编辑 (opens new window)
上次更新: 2023/12/15, 15:49:57