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

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

  • 相关阅读:
    linux下的进程
    进程间通讯
    const关键字
    关于嵌入式web服务器
    指针
    内存管理(malloc和free的用法)
    关于read和fread
    C库的制作
    C语言考试
    docker 配置阿里云镜像加速
  • 原文地址:https://www.cnblogs.com/reboot329/p/5956092.html
Copyright © 2020-2023  润新知