[LeetCode] 98. Verification binary search tree

topic

Given a binary tree to determine if it is a valid binary search tree.

Suppose a binary search tree having the following characteristics:

Left child node of the tree contains only less than the current node number.
Right subtree contain only greater than the number of nodes of the current node.
All left subtree and right subtree itself must also be binary search tree.

Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/validate-binary-search-tree
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

answer

By the title, preorder is strictly incremental, it is BST.
No need to store the results in order traversal, simply comparing the sequences preorder two elements adjacent to process.

Code

public static boolean isValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curNode = root;
        long maxVal = Long.MIN_VALUE;
        while (curNode != null || !stack.isEmpty()) {//
            while (curNode != null) {
                stack.push(curNode);
                curNode = curNode.left;
            }
            curNode = stack.pop();
            if (curNode.val > maxVal) {
                maxVal = curNode.val;
                curNode = curNode.right;//
            } else {
                return false;
            }
        }
        return true;
    }

Guess you like

Origin www.cnblogs.com/coding-gaga/p/11823573.html