226. Invert Binary Tree[Easy]

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Constraints:

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

Example
image

Input: root = [4,2,7,1,3,6,9]
Output: [4,7,2,9,6,3,1]

思路

遍历所有节点,置换左右子树

题解

    public TreeNode invertTree(TreeNode root) {
        if (root == null) 
            return null;
        
        invertTree(root.left);
        invertTree(root.right);

	// 置换左右子树
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        return root;
    }
posted @ 2023-02-01 14:07  AaronTanooo  阅读(19)  评论(0)    收藏  举报