226. Invert Binary Tree

题目:

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.

链接: http://leetcode.com/problems/invert-binary-tree/ 

2/28/2017

 1 public class Solution {
 2     public TreeNode invertTree(TreeNode root) {
 3         if (root == null) return root;
 4         TreeNode tmp = new TreeNode(0);
 5         if (root.left != null || root.right != null) {
 6             tmp = root.right;
 7             root.right = root.left;
 8             root.left = tmp;
 9         }
10         if (root.left != null) invertTree(root.left);
11         if (root.right != null) invertTree(root.right);
12         return root;
13     }
14 }

迭代的写法留给二刷?

posted @ 2017-03-01 04:26  panini  阅读(109)  评论(0编辑  收藏  举报