156. Binary Tree Upside Down

比较基础的题,用了recursive方法。

public class Solution 
{
    TreeNode prev = null;
    public TreeNode upsideDownBinaryTree(TreeNode root) 
    {
        if(root == null) return null;
        if(root.left == null && root.right == null) return root;
        
        helper(root);
        return prev;
    }
    
    public void helper(TreeNode root) 
    {
        if(root == null) return;
        if(root.left == null) prev = root;
        if(root.left == null && root.right == null) return;
        
        helper(root.left);
        
        root.left.left = root.right;
        root.left.right = root;
        root.left = null;
        root.right = null;
        
    }
    

}

一般还有iterative的办法,然而没做出来。。。。。。。



我在一刷的时候说到 "比较基础的"..

我以前就这么屌了= =? 现在做还想了一会,才照着题里给的图改出来的。

这个题reverse linked list如出一辙。。感觉是个套路啊。。

recursion:

public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == null) return root;
        TreeNode temp = upsideDownBinaryTree(root.left);
        root.left.right = root;
        root.left.left = root.right;
        root.left = null;
        root.right = null;
        return temp;
    }
}

iteration:

做得突出一个迷糊……基本也是对照例子里的图一个一个改的。

最后返还的指针试了一下TEMP,不对。。试了下LEFT,不对。。试了下RIGHT,卧槽对了。

其实Right是保留上一个的TEMP,所以应该返还Right.....

public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == null) return root;
        TreeNode temp = root;
        TreeNode left = null;
        TreeNode right = null;
        
        while (temp != null) {
            TreeNode nextLeft = temp.left;
            temp.left = left;
            left = temp.right;
            temp.right = right;
            right = temp;
            temp = nextLeft;
        }
        return right;
    }
}

我太牛逼了,一刷那句”比较基础的题“让我傲视群雄,也让现在的自己汗颜= =

posted @ 2016-10-13 12:55  哇呀呀..生气啦~  阅读(184)  评论(0编辑  收藏  举报