538. 把二叉搜索树转换为累加树
给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater
Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。例如:
输入: 原始二叉搜索树:
5
/
2 13输出: 转换为累加树:
18
/
20 13注意:本题和 1038:
https://leetcode-cn.com/problems/binary-search-tree-to-greater-sum-tree/
相同
适用于所有的树的转换成累加树
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
lis=[]
def helper(root):
if not root:
return
lis.append(root.val)
if root.left:
helper(root.left)
if root.right:
helper(root.right)
helper(root)
lis.sort(reverse=True)
def helper2(root):
if not root:
return
idx=lis.index(root.val)
plus=sum(lis[:idx])
root.val+=plus
if root.left:
helper2(root.left)
if root.right:
helper2(root.right)
helper2(root)
return root
- 先遍历一遍树结构,把每个节点的值取出来
- 再遍历一遍树,使每一个节点原来的节点值加上所有大于它的节点值之和。
利用二叉搜索树的性质
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树: 若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值; 它的左、右子树也分别为二叉排序树。二叉搜索树作为一种经典的数据结构,它既有链表的快速插入与删除操作的特点,又有数组快速查找的优势;所以应用十分广泛,例如在文件系统和数据库系统一般会采用这种数据结构进行高效率的排序与检索操作。 [1]
递归
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
self.plus=0
def helper(root):
if not root:
return
if root.right:
helper(root.right)
self.plus+=root.val
root.val=self.plus
if root.left:
helper(root.left)
helper(root)
return root
- 因为是二叉搜索树的缘故,我们只需要从右子树->根节点->左子树这样的顺序遍历得到的数都是按照从大到小的顺序的数
- 因此对于一个节点变换后的数字就是该节点的数字加上之前遍历过的节点的数字之和
- 通过一个中序遍历就实现了上述所说的过程
迭代
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
stack=[]
cur =root
plus=0
while stack or cur:
while cur:
stack.append(cur)
cur=cur.right
cur=stack.pop()
plus+=cur.val
cur.val=plus
cur=cur.left
return root
- 迭代的方式实现中序遍历
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def convertBST(self, root: TreeNode) -> TreeNode:
stack=[(root,0)]
plus=0
while stack:
node,color=stack.pop()
if not node:
continue
if color ==0:
stack.append((node.left,0))
stack.append((node,1))
stack.append((node.right,0))
else:
plus+=node.val
node.val=plus
return root