/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

//Using in-order-traversal method to do it. 

public class Solution {
    private ArrayList<Integer> myArray = new ArrayList<Integer>();

    public boolean isValidBST(TreeNode root) {

        if (root==null || (root.left==null&&root.right==null)){
            return true;
        }

        inOrder(root);

        int temp = myArray.get(0);
        int cur;

        for(int i=1; i<myArray.size(); i++){
            cur = myArray.get(i);
            if (cur<=temp) {
                return false;
            }
            temp = cur;
        } 
        System.out.println(myArray);
        return true;

    }

    private void inOrder(TreeNode root) {
        if (root.left != null) {
            inOrder(root.left);
        }
        if (root != null) {
            myArray.add(root.val);
        }
        if (root.right != null) {
            inOrder(root.right);
        }  
        return;        
    }
}

results matching ""

    No results matching ""