码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode -- Invert Binary Tree

时间:2015-09-27 00:02:39      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:

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;
    }
}

 

LeetCode -- Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/little-YTMM/p/4841554.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!