leetcode:Binary Tree Upside Down

本文介绍了一种特殊的二叉树转换问题——将特定形态的二叉树上下颠倒,并详细阐述了递归和非递归两种实现方法。通过实例解析了算法的设计思路与具体步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题描述

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  

 

原问题链接:https://leetcode.com/problems/binary-tree-upside-down/

 

问题分析

  对于二叉树的问题,我们比较容易想到的是看能否有什么递归的方式来解决这个问题。这里我们可以利用这么一个思路:在某个节点的时候,我们把它的左子树颠倒,在颠倒完成后,原来那个左子树的左右子节点分别指向原来的根节点和原来的右兄弟节点。这样,在实现的时候,我们需要保存有一个当前子节点的上一级节点,在返回的时候设置。

  详细的代码实现如下:

 

public class Solution {
    public TreeNode upsideDownBinaryTree(TreeNode root) {
        if(root == null) return null;
        TreeNode parent = root, left = root.left, right = root.right;
        if(left != null) {
            TreeNode ret = upsideDownBinaryTree(left);
            left.left = right;
            left.right = parent;
            return ret;
        }
        return root;
    }
}

 

非递归方式实现

  基于上述递归实现的代码也可以转换成非递归的迭代实现方式,这种方式的实现如下:

 

public TreeNode upsideDownBinaryTree(TreeNode root) {
		TreeNode node = root, parent = null, right = null;
		while (node != null) {
			TreeNode left = node.left;
			node.left = right;
			right = node.right;
			node.right = parent;
			parent = node;
			node = left;
		}
		return parent;
	}

 

总结

  对二叉树的上下颠倒转换比较复杂,需要结合递归和一些树的关系进行转换。最好结合树的结构图进行详细的转换推导。 

 

参考材料

http://bangbingsyb.blogspot.jp/2014/11/leetcode-binary-tree-upside-down.html

http://blog.youkuaiyun.com/whuwangyi/article/details/43186045 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值