My java solution to separate the Inorder traversal skeleton from actual visitor logic


  • 0
    T

    I think this looks nicer, once u mention "basically this is in-order traversal, then what we do for the traversal is ..."

      /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     
     class Pair {
         
         public TreeNode tr;
         public boolean secondTime;
         
         public Pair(TreeNode tr) {this.tr = tr; secondTime = false;}
     }
     
     
     interface Visitor {
         boolean visit(TreeNode n);
     }
    public class Solution {
        int last = Integer.MIN_VALUE;
        boolean initialized = false;
        public boolean isValidBST(TreeNode root) {
            if (root == null) return true;
            
            return inOrder(root, new Visitor(){
                boolean initialized = false;
                int last ;
                public boolean visit(TreeNode n) {
                    if (initialized && n.val <= last) return false;
                    
                    initialized = true;
                    last = n.val;
                    
                    return true;
                }  
            });
        }
        
        boolean inOrder(TreeNode n, Visitor visitor) {
            if (n == null) return true;
            return inOrder(n.left, visitor ) && visitor.visit(n) && inOrder(n.right, visitor);
            
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.