题目:
翻转一棵二叉树。
题解:
1.递归
翻转二叉树必须要遍历,前序、后序遍历都可以,中序不可以,因为先左子树,再翻转root左右子树,这时的右子树其实是之前的左子树,最后翻转此时的右子树其实是翻转之前的左子树,这样左子树被翻转了两次。
/**
* 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;
}
swap(root); //根
invertTree(root.left); //左
invertTree(root.right); //右
return root;
}
public void swap(TreeNode root) {
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}
}
参考:代码随想录