diff --git a/SumRoot.java b/SumRoot.java new file mode 100644 index 00000000..6410896d --- /dev/null +++ b/SumRoot.java @@ -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); + } +} diff --git a/SumRootRec.java b/SumRootRec.java new file mode 100644 index 00000000..3af670d6 --- /dev/null +++ b/SumRootRec.java @@ -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); + } +} diff --git a/ValidateBST.java b/ValidateBST.java new file mode 100644 index 00000000..390b1621 --- /dev/null +++ b/ValidateBST.java @@ -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); + + } +} diff --git a/ValidateBSTRecursive.java b/ValidateBSTRecursive.java new file mode 100644 index 00000000..66a687c2 --- /dev/null +++ b/ValidateBSTRecursive.java @@ -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); + } +} \ No newline at end of file