LeetCode.226.Invert Binary Tree 反转二叉树

题目描述

226 Invert Binary Tree https://leetcode-cn.com/problems/invert-binary-tree/

Invert a binary tree.

Example:

Input:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

Output:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

Trivia: This problem was inspired by this original tweet by Max Howell:

Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f* off.


解题过程

反转二叉树,典型的递归

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

GitHub代码

algorithms/leetcode/leetcode/_226_InvertBinaryTree.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_226_InvertBinaryTree.java