Leetcode 538.把二叉搜索树转换为累加树(Convert BST to Greater Tree)

Leetcode 538.把二叉搜索树转换为累加树

1 题目描述(Leetcode题目链接

  给定一个二叉搜索树(Binary Search Tree),把它转换成为累加树(Greater Tree),使得每个节点的值是原来的节点值加上所有大于它的节点值之和。

输入: 原始二叉搜索树:
              5
            /   \
           2     13

输出: 转换为累加树:
             18
            /   \
          20     13

2 题解

  根据二叉搜索树的性质,本题为中序遍历的逆序版,按照”右根左“的顺序遍历,同时用一个数字记录累加结果,更新节点值。

# 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 = []
        num = 0
        node = root
        while node or stack:
            while node:
                stack.append(node)
                node = node.right
            node = stack.pop()
            node.val += num
            num = node.val
            node = node.left
        return root
发布了264 篇原创文章 · 获赞 63 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/qq_39378221/article/details/105115378