0226. Invert Binary Tree

226. Invert Binary Tree #

题目 #

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

思路 #

代码 #

递归 #

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 || (root.left == null && root.right == null)) return root;
        
        invertTree(root.left);
        invertTree(root.right);
        TreeNode ptr = root.left;
        root.left = root.right;
        root.right = ptr;
        
        return root;
    }
}