二刷156. Binary Tree Upside Down

Medium
不完全懂

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == 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;
    }
}

这道题还有iterative的写法:

二刷156. Binary Tree Upside Down_第1张图片
image.png
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null){
            return null;
        }
        TreeNode curt = root;
        TreeNode prev = null;
        TreeNode next = null;
        TreeNode temp = null;
        while (curt != null){
            next = curt.left;
            curt.left = temp;
            temp = curt.right;
            curt.right = prev;
            prev = curt;
            curt = next;
        }
        return prev;
    }
}

你可能感兴趣的:(二刷156. Binary Tree Upside Down)