[leetcode] Binary Tree Upside Down

Posted jdflyfly

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[leetcode] Binary Tree Upside Down相关的知识,希望对你有一定的参考价值。

 

思路:递归实现,注意翻转的规律,以左子树作为根,找到左子树最右边的节点作为原有right子树和根的父节点。

 

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

 

以上是关于[leetcode] Binary Tree Upside Down的主要内容,如果未能解决你的问题,请参考以下文章

[Leetcode] Binary search tree --Binary Search Tree Iterator

Leetcode[110]-Balanced Binary Tree

[Leetcode] Binary tree -- 501. Find Mode in Binary Search Tree

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

LeetCode 110. Balanced Binary Tree 递归求解

[Leetcode] Balanced Binary Tree