Accepted 16ms c++ solution with binary tree inorder traversal.


  • 0
    class Solution {
    public:
        bool isValidBST(TreeNode *root) {
            if (root == NULL)
                return true;
            std::stack<TreeNode *> nodes;
            nodes.push(root);
    		int val;
    		bool first = true;
            while (!nodes.empty()) {
                TreeNode *tmp = nodes.top();
                if (tmp->left != NULL) {
                    nodes.push(tmp->left);
                    tmp->left = NULL;
                }
                else {
    				if (first)
    					first = false;
    				else if (tmp->val <= val)
    					return false;
    				val = tmp->val;
                    nodes.pop();
                    if (tmp->right != NULL)
                        nodes.push(tmp->right);
                }
            }
            return true;
        }
    };

  • 0
    M
            if (tmp->left != NULL) {
                nodes.push(tmp->left);
                tmp->left = NULL;
            }
    

    would tmp->left = NULL modify the Tree ?


Log in to reply
 

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