zoukankan      html  css  js  c++  java
  • 【LeetCode & 剑指offer刷题】树题13:Validate Binary Search Tree

    【LeetCode & 剑指offer 刷题笔记】目录(持续更新中...)

    Validate Binary Search Tree

    Validate Binary Search Tree
    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:
    Input:
    2
    /
    1 3
    Output: true
    Example 2:
    5
    /
    1 4
    /
    3 6
    Output: false
    Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value
    is 5 but its right child's value is 4.

    C++
     
    /**
     * 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;
           
            stack<TreeNode*> s;
            TreeNode* p = root;
            TreeNode* pre = NULL;
           
            while(!s.empty() || p)
            {
                if(p)
                {
                    s.push(p);
     
                    p = p->left;
                }
                else
                {
                    p = s.top();
                    if(pre != NULL && p->val <= pre->val) return false; //看是否为升序
                    pre = p; //保存已经访问的结点
                    s.pop();
                    
                    p = p->right;
                }
            }
           
            return true;
        }
    };
     
    //参考:
            while(p != nullptr || !s.empty())
            {
                if(p != nullptr) //当左结点不为空时
                {
                    s.push(p); //入栈
     
                    p = p->left; //指向下一个左结点
                }
                else            //当左结点为空时
                {
                    p = s.top();
                    path.push_back(p->val); //访问栈顶元素(父结点)
                    s.pop();         //出栈
                   
                    p = p->right;    //指向右结点
                }
            }
     
     
  • 相关阅读:
    雅虎天气API调用
    HttpOperater
    HttpOperater-模拟HTTP操作类
    页面局部加载,适合Ajax Loading场景(Demo整理)
    FTPHelper-封装FTP的相关操作
    使用SOCKET实现TCP/IP协议的通讯
    IIS目录禁止执行权限
    Oracle10g 安装步骤
    SQL Server 2008、SQL Server 2008R2 自动备份数据库
    SQL列转行
  • 原文地址:https://www.cnblogs.com/wikiwen/p/10225840.html
Copyright © 2011-2022 走看看