?LeetCode刷題實戰(zhàn)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
????????"""
????????#每一個節(jié)點變成其左孩子的右節(jié)點
????????if?not?root or?(not?root.left and?not?root.right):
????????????return?root
?
????????newroot = self.upsideDownBinaryTree(root.left)
????????# self.upsideDownBinaryTree(root.right) 右孩子不用處理 因為要么不存在要么是葉節(jié)點
????????
????????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
????????"""
????????#每一個節(jié)點變成其左孩子的右節(jié)點
????????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
