Leetcode - Binary Tree Upside Down

My code:

/**
 * 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 upsideDownBinaryTree(TreeNode root) {
        if (root == null || (root.left == null && root.right == null)) {
            return root;
        }
        
        TreeNode newRoot = upsideDownBinaryTree(root.left);
        root.left.left = root.right;
        root.left.right = root;
        root.left = null;
        root.right = null;
        
        return newRoot;
    }
}

iteration:
My code:

/**
 * 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 upsideDownBinaryTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        
        TreeNode curr = root;
        TreeNode pre = null;
        TreeNode temp = null;
        TreeNode next = null;
        while (curr != null) {
            next = curr.left;
            curr.left = temp;
            temp = curr.right;
            curr.right = pre;
            pre = curr;
            curr = next;
        }
        
        return pre;
    }
}

reference:
https://discuss.leetcode.com/topic/40924/java-recursive-o-logn-space-and-iterative-solutions-o-1-space-with-explanation-and-figure/2

这道题目都看不懂。。
直到看了代码,自己测试了下,才逐渐懂到底要我们干什么。。
然后所有的右节点,要么是有兄弟结点的叶子结点,要么是null
所以这棵树是 Invalid 的。
[1,2,3,4,5,6,7]
所以只需要考虑一直向左就行。
recursion is from bottom to top
iteration is from top to bottom

Anyway, Good luck, Richardo! -- 09/07/2016

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 13,183评论 0赞 33
  • 偶然看了一老同学,还在行山游水,自由随行。突发感慨,这两年我在忙什么呢,空间里几乎都是儿子的日记相片,我的生活也是...
    郑红阅读 168评论 0赞 0
  • 当身边的朋友说你是疯子的时候成功离你不远了! ------美歌美词
    月牙博客阅读 348评论 0赞 3
  • 因为这几天中考放假,女儿晚上都比较晚睡觉。所以早上就不想起床,本来就起来比较晚,加上脚上有伤,比较讲究的她把包扎的...
    浅笑嫣然love阅读 424评论 2赞 1
  • 我们是一群平凡的人,身处在平凡之中,做着平凡的事,说着一些无关痛痒的话,因为,我们实在太平凡。我们希望你闭嘴鸡汤喝...
    苏灏阅读 249评论 0赞 1

友情链接更多精彩内容