mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 00:43:04 +08:00
@ -177,6 +177,8 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
## Java
|
## Java
|
||||||
|
**递归**
|
||||||
|
|
||||||
```Java
|
```Java
|
||||||
class Solution {
|
class Solution {
|
||||||
int sum;
|
int sum;
|
||||||
@ -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
|
## Python
|
||||||
递归法(版本一)
|
递归法(版本一)
|
||||||
|
Reference in New Issue
Block a user