LeetCode刷题实战156:上下翻转二叉树
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
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
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
parent, sibling = None, None
while root:
tmp = root.left
root.left = sibling
sibling = root.right
root.right = parent
parent = root
root = tmp
return parent