|
| 1 | +## 538. 把二叉搜索树转换为累加树 |
| 2 | +> https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ |
| 3 | +
|
| 4 | + |
| 5 | +### Java |
| 6 | +```java |
| 7 | +/* |
| 8 | + * @Author: Goog Tech |
| 9 | + * @Date: 2020-08-16 12:23:26 |
| 10 | + * @LastEditTime: 2020-08-16 12:30:19 |
| 11 | + * @Description: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ |
| 12 | + * @FilePath: \leetcode-googtech\#538. Convert BST to Greater Tree\Solution.java |
| 13 | + * @WebSite: https://algorithm.show/ |
| 14 | + */ |
| 15 | + |
| 16 | +/* |
| 17 | + * @lc app=leetcode.cn id=538 lang=java |
| 18 | + * |
| 19 | + * [538] 把二叉搜索树转换为累加树 |
| 20 | + */ |
| 21 | + |
| 22 | +// @lc code=start |
| 23 | +/** |
| 24 | + * Definition for a binary tree node. |
| 25 | + * public class TreeNode { |
| 26 | + * int val; |
| 27 | + * TreeNode left; |
| 28 | + * TreeNode right; |
| 29 | + * TreeNode(int x) { val = x; } |
| 30 | + * } |
| 31 | + */ |
| 32 | +class Solution { |
| 33 | + |
| 34 | + private int sum = 0; |
| 35 | + |
| 36 | + // 利用反序中序遍历解题,注: 二叉搜索树的左子树 < 根 < 右子树 |
| 37 | + public TreeNode convertBST(TreeNode root) { |
| 38 | + if(root != null) { |
| 39 | + // 遍历右子树 |
| 40 | + convertBST(root.right); |
| 41 | + // 对遍历到的每个节点值进行累加,并将其结果赋值给当前节点的值 |
| 42 | + sum = sum + root.val; |
| 43 | + root.val = sum; |
| 44 | + // 遍历左子树 |
| 45 | + convertBST(root.left); |
| 46 | + } |
| 47 | + return root; |
| 48 | + } |
| 49 | +} |
| 50 | +// @lc code=end |
| 51 | +``` |
| 52 | + |
| 53 | +### Python |
| 54 | +```python |
| 55 | +''' |
| 56 | +Author: Goog Tech |
| 57 | +Date: 2020-08-16 12:10:39 |
| 58 | +LastEditTime: 2020-08-16 12:30:38 |
| 59 | +Description: https://leetcode-cn.com/problems/convert-bst-to-greater-tree/ |
| 60 | +FilePath: \leetcode-googtech\#538. Convert BST to Greater Tree\Solution.py |
| 61 | +WebSite: https://algorithm.show/ |
| 62 | +''' |
| 63 | +# |
| 64 | +# @lc app=leetcode.cn id=538 lang=python |
| 65 | +# |
| 66 | +# [538] 把二叉搜索树转换为累加树 |
| 67 | +# |
| 68 | + |
| 69 | +# @lc code=start |
| 70 | +# Definition for a binary tree node. |
| 71 | +# class TreeNode(object): |
| 72 | +# def __init__(self, x): |
| 73 | +# self.val = x |
| 74 | +# self.left = None |
| 75 | +# self.right = None |
| 76 | + |
| 77 | +class Solution(object): |
| 78 | + |
| 79 | + def __init__(self): |
| 80 | + self.total = 0 |
| 81 | + |
| 82 | + # 利用反序中序遍历解题,注: 二叉搜索树的左子树 < 根 <右子树 |
| 83 | + def convertBST(self, root): |
| 84 | + """ |
| 85 | + :type root: TreeNode |
| 86 | + :rtype: TreeNode |
| 87 | + """ |
| 88 | + if root is not None: |
| 89 | + # 遍历右子树 |
| 90 | + self.convertBST(root.right) |
| 91 | + # 对遍历到的每个节点值进行累加,并将其结果赋值给当前节点的值 |
| 92 | + self.total = self.total + root.val |
| 93 | + root.val = self.total |
| 94 | + # 遍历左子树 |
| 95 | + self.convertBST(root.left) |
| 96 | + return root |
| 97 | + |
| 98 | +# @lc code=end |
| 99 | +``` |
0 commit comments