156 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.

For example:

Given a binary tree {1,2,3,4,5},

    1

   / \

  2   3

 / \

4   5

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

   4

  / \

 5   2

    / \

   3   1  

 思路1:

这道题让我们把一棵二叉树上下颠倒一下,而且限制了右节点要么为空要么一定会有对应的左节点。上下颠倒后原来二叉树的最左子节点变成了根节点,其对应的右节点变成了其左子节点,其父节点变成了其右子节点,相当于顺时针旋转了一下。对于一般树的题都会有迭代和递归两种解法,这道题也不例外,那么我们先来看看递归的解法。对于一个根节点来说,我们的目标是将其左子节点变为根节点,右子节点变为左子节点,原根节点变为右子节点,那么我们首先判断这个根节点是否存在,且其有没有左子节点,如果不满足这两个条件的话,直接返回即可,不需要翻转操作。那么我们不停的对左子节点调用递归函数,直到到达最左子节点开始翻转,翻转好最左子节点后,开始回到上一个左子节点继续翻转即可,直至翻转完整棵树

代码1:

public class UpsideTree {
    public static TreeNode upSideDown(TreeNode root) {
        if (root == null || root.left == null)
            return root;
        TreeNode l = root.left;
        TreeNode r = root.right;
        TreeNode res = upSideDown(l);
        l.left = r;
        l.right = root;
        root.left = null;
        root.right = null;
        return res;
    }
}

思路2:

下面我们来看迭代的方法,和递归方法相反的时,这个是从上往下开始翻转,直至翻转到最左子节点

代码2:

public class UpsideTree {
    public static TreeNode upSideDown(TreeNode root) {
        if (root == null || root.left == null)
            return root;
        TreeNode curr = root, prev = null, temp = null, next = null;
        while (curr != null) {
            next = curr.left;
            curr.left = temp;
            temp = curr.right;
            curr.right = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值