翻转二叉树

翻转一棵二叉树。
示例:
输入:
    4
   /  \
   2    7
  /  \    /  \
1    3  6    9
输出:
    4
   /   \
  7    2
 /  \    /  \
9   6  3   1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/invert-binary-tree

分析:
此题比较简单,直接遍历下去,修改左右子节点位置就好。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return root;
        invertTree(root.left);
        invertTree(root.right);
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
}

稍微简化一点代码可以写成这样,不过几乎没差别。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode invertTree(TreeNode root) {
        if(root == null) return root;
        TreeNode temp = root.right;
        root.right = invertTree(root.left);
        root.left = invertTree(temp);
        return root;
    }
}

再重写一遍

class Solution {
    public TreeNode invertTree(TreeNode root) {
        if (root == null) return root;
        TreeNode temp = invertTree(root.left);
        root.left = invertTree(root.right);
        root.right = temp;
        return root;
    }
}

你可能感兴趣的:(Leetcode题解,二叉树,翻转二叉树,java)