Leetcode - Invert Binary Tree

Question

Invert a binary tree.

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

to

     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 fuck off.

Java Code

public TreeNode invertTree(TreeNode root) {
    if(root == null || root.left == null && root.right == null) 
        return root;
    else {
        invertTree(root.left);//反转左子树
        invertTree(root.right);//反转右子树
        TreeNode node = root.left;//交换当前节点的左右子节点
        root.left = root.right;
        root.right = node;
    }

    return root;
}

你可能感兴趣的:(LeetCode,tree,invert)