[Leetcode] Binary Tree Upside Down 二叉树上下调个儿

Binary Tree Upside Down

Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.node

For example:
Given a binary tree {1,2,3,4,5},ide

1
   / \
  2   3
 / \
4   5

return the root of the binary tree [4,5,2,#,#,3,1].code

4
  / \
 5   2
    / \
   3   1

递归

复杂度

O(N) 时间 O(N) 空间递归

思路

啥叫upsidedown?ip

a                         b
   / \        ----->         / \
  b   c                     c   a

upsidedown的意思就是把这三个node顺时针换一下位置。
整个树最后的顶点是原树最左的孩子。
假设递归来到了a为root的这一层(如上图左),a的左边返回了新的树根b,
注意此时b表明一个子树,c也表明一个子树
咱们要把b扶持登基为根,而后c和a往哪放呢?b是一颗子树啊,人家已经有左右孩子了,容不下c和a了,分析题目给的例子,题意要把他们放到b的最右的孩子下面
把这个最右的孩子叫作rightMostNode,rightMostNode是个叶子节点没有左右孩子喔,因而咱们把c拖家带口(带着他的孩子们)挂在rightMostNode的左边,把a诛九族后(为了不造成cycle,咱们只要a本身,把他的孩子(b和c)都去掉,即从新实例化一个a,左右孩子为Null)挂在他的右边,返回新的根(b的根)便可it

注意

这题理解起来费劲io

代码

public class Solution {
    //返回新的树根
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if (root == null || root.left == null)
            return root;
        TreeNode newRoot = upsideDownBinaryTree(root.left);//新树根在最左
        TreeNode rightMostIterator = newRoot;//找新根的最右,挂两个旋转得来的的孩子
        while (rightMostIterator.right != null) {
            rightMostIterator = rightMostIterator.right;
        }
        rightMostIterator.left = root.right;//原右孩子拖家带口投奔新根的左边
        rightMostIterator.right = new TreeNode(root.val);//原root诛九族去右边
        return newRoot;//返回新根
    }
}
相关文章
相关标签/搜索