-
Notifications
You must be signed in to change notification settings - Fork 5
/
ConvertBstToGreaterTree.java
51 lines (43 loc) · 1.35 KB
/
ConvertBstToGreaterTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Problem Statement:
Given a Binary Search Tree (BST), convert it to a Greater Tree such that every key of the original BST is changed to the original key plus sum of all keys greater than the original key in BST.
Problem Link:
Convert BST to Greater Tree https://leetcode.com/problems/convert-bst-to-greater-tree/description/
Solution:
https://github.com/sunnypatel165/leetcode-again/blob/master/solutions/ConvertBstToGreaterTree.java
Author:
Sunny Patel
https://github.com/sunnypatel165
https://www.linkedin.com/in/sunnypatel165/
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int sum =0;
public TreeNode convertBST(TreeNode root) {
return convertBstIterative(root);
}
public TreeNode convertBstIterative(TreeNode root){
TreeNode node = root;
Stack stack = new Stack();
while(!stack.isEmpty() || node!=null){
while(node!=null){
stack.push(node.right);
node = node.right;
}
node = (TreeNode)stack.pop();
node.val += sum;
sum +=node.val;
node = node.left;
}
return root;
}
}