Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 926008c

Browse files
adding java iteraion
新增java統一迭代法
1 parent f7e280e commit 926008c

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

‎problems/0538.把二叉搜索树转换为累加树.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,8 @@ public:
177177

178178

179179
## Java
180+
**递归**
181+
180182
```Java
181183
class Solution {
182184
int sum;
@@ -198,6 +200,42 @@ class Solution {
198200
}
199201
}
200202
```
203+
**迭代**
204+
205+
```Java
206+
class Solution {
207+
//DFS iteraion統一迭代法
208+
public TreeNode convertBST(TreeNode root) {
209+
int pre = 0;
210+
Stack<TreeNode> stack = new Stack<>();
211+
if(root == null) //edge case check
212+
return null;
213+
214+
stack.add(root);
215+
216+
while(!stack.isEmpty()){
217+
TreeNode curr = stack.peek();
218+
//curr != null的狀況,只負責存node到stack中
219+
if(curr != null){
220+
stack.pop();
221+
if(curr.left != null) //
222+
stack.add(curr.left);
223+
stack.add(curr); //
224+
stack.add(null);
225+
if(curr.right != null) //
226+
stack.add(curr.right);
227+
}else{
228+
//curr == null的狀況,只負責做單層邏輯
229+
stack.pop();
230+
TreeNode temp = stack.pop();
231+
temp.val += pre;
232+
pre = temp.val;
233+
}
234+
}
235+
return root;
236+
}
237+
}
238+
```
201239

202240
## Python
203241
**递归**

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /