zoukankan      html  css  js  c++  java
  • 98. Validate Binary Search Tree (Tree; DFS)

     Given a binary tree, determine if it is a valid binary search tree (BST).

    Assume a BST is defined as follows:

        The left subtree of a node contains only nodes with keys less than the node's key.
        The right subtree of a node contains only nodes with keys greater than the node's key.
        Both the left and right subtrees must also be binary search trees.

    Example 1:

        2
       /
      1   3

    Binary tree [2,1,3], return true.

    Example 2:

        1
       /
      2   3

    Binary tree [1,2,3], return false.

    思路:由于Binary Tree的中序遍历结果是正序,所以可以检查中序遍历的结果是否递增

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        bool isValidBST(TreeNode* root) {
            if(root==NULL) return true;
            TreeNode* pre = NULL; //we don't need to save all nodes, only a previous node is enough to know whether it's an increase sequence
            return inOrderTraverse(root,pre);
        }
        
        bool inOrderTraverse(TreeNode* root, TreeNode* &pre){ //important to use &, otherwise new object will use a new address and the result won't bring back to caller
            //visit left child
            if(root->left) 
                if(!inOrderTraverse(root->left,pre))
                    return false;
            
            //visit root
            if(pre==NULL) pre = new TreeNode(root->val);
            else if(root->val > pre->val) pre->val = root->val;
            else return false;
            
            //visit right child
            if(root->right) return inOrderTraverse(root->right, pre);
            else return true;
        }
    };
  • 相关阅读:
    php中的多态
    面向对象的继承与组合
    PHP中的__call和__callStatic方法
    PHP中的__set和__get方法
    PHP中对象的本质
    mysql字符串查找(统计客源)
    linux查看文件大小
    mysql常用字符串操作函数大全,以及实例
    mysql滑动订单问题
    mysql列反转Pivoting
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/6063363.html
Copyright © 2011-2022 走看看