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.

 

Analysis:

问题描述:给出一个二叉树,然后将它的左右子树置换。

思路:这种题目首先应该反射到递归。用递归有两个条件:return 语句的书写和递归语句的书写。在这道题目中,只要一个节点有任何左节点或者右节点,则应该将他们置换。因此只要非空就置换

 

Answer:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode invertTree(TreeNode root) {
      if(root == null)
              return root;
      TreeNode t = root.left;
      root.left = root.right;
      root.right = t;
      invertTree(root.left);
      invertTree(root.right);
      return root;
    }
}

 

posted @ 2015-09-26 23:13  江湖小妞  阅读(152)  评论(0编辑  收藏  举报