669.修剪二叉搜索树
class Solution ( object ) :
def trimBST ( self, root, low, high) :
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: TreeNode
"""
if not root:
return None
while root and ( root. val< low or root. val> high) :
if root. val< low:
root = root. right
elif root. val> high:
root = root. left
cur = root
while cur:
while cur. left and cur. left. val< low:
cur. left = cur. left. right
cur = cur. left
cur = root
while cur:
while cur. right and cur. right. val> high:
cur. right = cur. right. left
cur = cur. right
return root
class Solution ( object ) :
def trimBST ( self, root, low, high) :
"""
:type root: TreeNode
:type low: int
:type high: int
:rtype: TreeNode
"""
if not root:
return None
if root. val< low:
return self. trimBST( root. right, low, high)
elif root. val> high:
return self. trimBST( root. left, low, high)
root. left = self. trimBST( root. left, low, high)
root. right = self. trimBST( root. right, low, high)
return root
108.将有序数组转换为二叉搜索树
class Solution ( object ) :
def sortedArrayToBST ( self, nums) :
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
root = TreeNode( val = nums[ len ( nums) / 2 ] )
root. left = self. sortedArrayToBST( nums[ : len ( nums) / 2 ] )
root. right = self. sortedArrayToBST( nums[ len ( nums) / 2 + 1 : ] )
return root
class Solution ( object ) :
def sortedArrayToBST ( self, nums) :
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
root = TreeNode( 0 )
nodeQue = collections. deque( [ root] )
leftQue = collections. deque( [ 0 ] )
rightQue = collections. deque( [ len ( nums) - 1 ] )
while nodeQue:
left = leftQue. popleft( )
right = rightQue. popleft( )
mid = left + ( right - left) // 2
node = nodeQue. popleft( )
node. val = nums[ mid]
if left <= mid- 1 :
node. left = TreeNode( 0 )
nodeQue. append( node. left)
leftQue. append( left)
rightQue. append( mid- 1 )
if right>= mid+ 1 :
node. right = TreeNode( 0 )
nodeQue. append( node. right)
leftQue. append( mid+ 1 )
rightQue. append( right)
return root
538.把二叉搜索树转换为累加树
class Solution ( object ) :
def convertBST ( self, root) :
"""
:type root: TreeNode
:rtype: TreeNode
"""
self. pre = 0
self. traversal( root)
return root
def traversal ( self, root) :
if not root:
return 0
self. traversal( root. right)
root. val += self. pre
self. pre = root. val
self. traversal( root. left)
class Solution ( object ) :
def convertBST ( self, root) :
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root:
return None
st = collections. deque( [ ] )
cur = root
pre = None
while cur or st:
while cur:
st. append( cur)
cur = cur. right
if not pre:
cur = st. pop( )
pre = cur
cur = cur. left
continue
if not cur:
cur = st. pop( )
cur. val += pre. val
pre = cur
cur = cur. left
return root
总结
涉及到二叉树的构造,无论普通二叉树还是二叉搜索树一定前序,都是先构造中节点。 求普通二叉树的属性,一般是后序,一般要通过递归函数的返回值做计算。如果单纯求深度就用前序 求二叉搜索树的属性,一定是中序了,要不白瞎了有序性了。