mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
Merge pull request #96 from Joshua-Lu/patch-12
添加 0538.把二叉搜索树转换为累加树 Java版本
This commit is contained in:
@ -173,20 +173,24 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
```java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
private int count = 0;
|
int sum;
|
||||||
public TreeNode convertBST(TreeNode root) {
|
public TreeNode convertBST(TreeNode root) {
|
||||||
convert(root);
|
sum = 0;
|
||||||
|
convertBST1(root);
|
||||||
return root;
|
return root;
|
||||||
}
|
}
|
||||||
|
|
||||||
private void convert (TreeNode root) {
|
// 按右中左顺序遍历,累加即可
|
||||||
if (root == null) return;
|
public void convertBST1(TreeNode root) {
|
||||||
convert(root.right);
|
if (root == null) {
|
||||||
count += root.val;
|
return;
|
||||||
root.val = count;
|
}
|
||||||
convert(root.left);
|
convertBST1(root.right);
|
||||||
|
sum += root.val;
|
||||||
|
root.val = sum;
|
||||||
|
convertBST1(root.left);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Reference in New Issue
Block a user