LeetCode-98.验证二叉搜索树(相关话题:深度优先搜索)

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

  • 节点的左子树只包含小于当前节点的数。
  • 节点的右子树只包含大于当前节点的数。
  • 所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

解题思路:

非递归中序遍历(用栈进行深度优先搜索)二叉树,是否为递增序列

Java代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        long tmp = Long.MIN_VALUE;
        Stack<TreeNode> stack = new Stack<>();

        while(null != root){
            stack.push(root);
            root = root.left;
        }

        while(!stack.isEmpty()){
            TreeNode treeNode = stack.pop();
            if(treeNode.val <= tmp)
                return false;
            tmp = treeNode.val;

            if(null != treeNode.right){
                stack.push(treeNode.right);
                while(null != stack.peek().left)
                    stack.push(stack.peek().left);
            }
        }

        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_38823568/article/details/82873298