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

你可能感兴趣的:(Leetcode - Binary Tree Upside Down)