Given a binary tree in which all right nodes are either leaf nodes with sibling nodes (left nodes with the same parent nodes) or empty, flip the binary tree up and down and turn it into a tree, and the original right nodes will be converted into left leaf nodes. Returns the new root.
题意
给定一个二叉树,其中所有的右节点要么是具有兄弟节点(拥有相同父节点的左节点)的叶节点,要么为空,将此二叉树上下翻转并将它变成一棵树, 原来的右节点将转换成左叶节点。返回新的根。样例解题
https://blog.csdn.net/qq_32424059/article/details/93920527
思路1:递归对于root而言,root应该成为root.left的右孩子,root.right应该成为root.left的左孩子。最后返回的是root.left处理之后的返回值。class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
#每一个节点变成其左孩子的右节点
if not root or (not root.left and not root.right):
return root
newroot = self.upsideDownBinaryTree(root.left)
# self.upsideDownBinaryTree(root.right) 右孩子不用处理 因为要么不存在要么是叶节点
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None
return newroot
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
#每一个节点变成其左孩子的右节点
if not root or (not root.left and not root.right):
return root
parent, sibling = None, None
while root:
tmp = root.left
root.left = sibling
sibling = root.right
root.right = parent
parent = root
root = tmp
return parent好了,今天的文章就到这里。