Leetcode 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
思路:由于对right kid节点的特殊要求:要么是空节点,要么是叶子节点而且他必有一个左sibling。但是一个left kid并不要求一定有sibling。从而可以得知每层最多有两个节点。这种树的形状类似梳子。
图1. 原始树
将其倒置之后我们得到图2。
图2. 加上两个空节点。
图3。把原来的root接上两个空节点。并保存他的左右Kid。
图4. 移动partent, node。回到类似图2的状态。
1 # Definition for a binary tree node. 2 # class TreeNode(object): 3 # def __init__(self, x): 4 # self.val = x 5 # self.left = None 6 # self.right = None 7 8 class Solution(object): 9 def upsideDownBinaryTree(self, root): 10 """ 11 :type root: TreeNode 12 :rtype: TreeNode 13 """ 14 node = root 15 parent = None 16 right = None 17 while node != None: 18 left = node.left 19 node.left = right 20 right = node.right 21 node.right = parent 22 parent = node 23 node = left 24 return parent