# LeetCode Invert Binary Tree题目分析

Invert a binary tree. 4 / \ 2 7 / \ / \1 3 6 9 to4 / \ 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.

Subscribe to see which companies asked this question.

# 分析

## Approach #1 (Recursive) [Accepted]

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

## Approach #2 (Iterative) [Accepted]

```public TreeNode invertTree(TreeNode root) {
if (root == null) return null;
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
}
return root;
}```

Paste_Image.png

381 篇文章35 人订阅

0 条评论

## 相关文章

### Leetcode 113 Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's su...

21050

8410

### Leetcode 230. Kth Smallest Element in a BST

Given a binary search tree, write a function kthSmallest to find the kth small...

241100

### Leetcode 173 Binary Search Tree Iterator

mplement an iterator over a binary search tree (BST). Your iterator will be ini...

22660

10220

18050

9020

12120

15330

11330