Skip to content
Open

trees-1 #1751

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions SumRoot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import java.util.*;

public class SumRoot {
int sum;
public int sumRoot(TreeNode root) {
helper(root, 0);
return sum;
}
private void helper(TreeNode root, int currSum) {
if (root==null) return;

currSum = currSum * 10 + root.val;
if (root.right == null && root.left==null) {
sum += currSum;
}
helper(root.left, currSum);
helper(root.right, currSum);
}
}
22 changes: 22 additions & 0 deletions SumRootRec.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
public class SumRootRec {
int sum;

public int sumNumbers(TreeNode root) {
return helper(root, 0);
}

public int helper(TreeNode root, int num) {
helper(root, 0);
return sum;
}
private void helper(TreeNode root, int currSum) {
if (root==null) return;

currSum = currSum * 10 + root.val;
if (root.right == null && root.left==null) {
sum += currSum;
}
helper(root.left, currSum);
helper(root.right, currSum);
}
}
23 changes: 23 additions & 0 deletions ValidateBST.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import java.util.*;

class ValidateBST {
boolean flag;
public boolean isValidBST(TreeNode root) {
this.flag = true;
helper(root, null, null);
return flag;
}
private void helper(TreeNode root, Integer min, Integer max) {
if (root==null) return;

helper(root.left, min, root.val);
if (min != null && root.val <= min) {
flag = false;
}
if (max != null && root.val >= max){
flag = false;
}
helper(root.right, root.val, max);

}
}
21 changes: 21 additions & 0 deletions ValidateBSTRecursive.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

class ValidateBSTRecursive {
boolean flag;
TreeNode prev;

public boolean validateBSTRecursive(TreeNode root) {
this.flag = true;
helper(root);
return flag;
}
private void helper(TreeNode root) {
if (root==null) return;
if (!flag) return;
helper(root.left);
if (prev != null && root.val <= prev.val){
flag = false;
}
prev = root;
helper(root.right);
}
}