Solution in C# via Inorder traversal


  • 0
    P
     public bool IsValidBST(TreeNode root)
            {
                List<int> lstVals = new List<int>();
                Helper(root, lstVals);
    
                for (int i = 0; i < lstVals.Count - 1; i++)
                {
                    if (lstVals[i] >= lstVals[i + 1]) return false;
                }
    
                return true;
            }
    
            /// <summary>
            /// Get the items of the list in inorder traversal.
            /// </summary>
            /// <param name="root"></param>
            /// <param name="items"></param>
            public void Helper(TreeNode root, List<int> items)
            {
                if (root == null)
                    return;
    
                Helper(root.left, items);
                items.Add(root.val);
                Helper(root.right, items);
            }
    

Log in to reply
 

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