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

[LeetCode] Invert Binary Tree

时间:2015-08-12 18:18:46      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:

Invert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9

to

     4
   /     7     2
 / \   / 9   6 3   1

     这道题呢=。=看着题目简介挺有意思的。哈哈哈。~说实话我真的很讨厌whiteboard上直接来代码。

     因为要翻转的BTS已经给出来了,灰常短小的一个啊~所以按照自己的喜好whatever交换就好了。

     因为这里BTS已经给出来了所以可以偷懒直接交换(毕竟这么短小),这个比较取巧。代码如下。

public class Solution {
    public TreeNode invertTree(TreeNode root) {
   
       //invert directly
	TreeNode left=root.left;
	TreeNode right=root.right;
	root.left=invertTree(right);
	root.right=invertTree(left);
	return root;

        //special case
        if(root==null){
          return null;
        }
    }
} 

 然后呢贴一个常规思维来的,这是program creek上的。我大概写了一下,懒得run了。就贴一个确定accepted的答案好了。

 这个就是踏踏实实一个一个看的。

public TreeNode invertTree(TreeNode root) {
    LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
 
    if(root!=null){
        queue.add(root);
    }
 
    while(!queue.isEmpty()){
        TreeNode p = queue.poll();
        if(p.left!=null)
            queue.add(p.left);
        if(p.right!=null)
            queue.add(p.right);
 
        TreeNode temp = p.left;
        p.left = p.right;
        p.right = temp;
    }
 
    return root;    
}

 

[LeetCode] Invert Binary Tree

标签:

原文地址:http://www.cnblogs.com/orangeme404/p/4724687.html

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