Skip to content

Commit

Permalink
Merge pull request youngyangyang04#2073 from Lozakaka/patch-9
Browse files Browse the repository at this point in the history
adding java iteration
  • Loading branch information
youngyangyang04 authored May 28, 2023
2 parents 5cbb991 + 926008c commit 9168b90
Showing 1 changed file with 38 additions and 0 deletions.
38 changes: 38 additions & 0 deletions problems/0538.把二叉搜索树转换为累加树.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,8 @@ public:


## Java
**递归**

```Java
class Solution {
int sum;
Expand All @@ -198,6 +200,42 @@ class Solution {
}
}
```
**迭代**

```Java
class Solution {
//DFS iteraion統一迭代法
public TreeNode convertBST(TreeNode root) {
int pre = 0;
Stack<TreeNode> stack = new Stack<>();
if(root == null) //edge case check
return null;

stack.add(root);

while(!stack.isEmpty()){
TreeNode curr = stack.peek();
//curr != null的狀況,只負責存node到stack中
if(curr != null){
stack.pop();
if(curr.left != null) //
stack.add(curr.left);
stack.add(curr); //
stack.add(null);
if(curr.right != null) //
stack.add(curr.right);
}else{
//curr == null的狀況,只負責做單層邏輯
stack.pop();
TreeNode temp = stack.pop();
temp.val += pre;
pre = temp.val;
}
}
return root;
}
}
```

## Python
递归法(版本一)
Expand Down

0 comments on commit 9168b90

Please sign in to comment.