zoukankan      html  css  js  c++  java
  • 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.

    Solution: Recursion. 1. Add lower & upper bound. O(n)
    2. Inorder traversal with one additional parameter (value of predecessor). O(n)

     1 /**
     2  * Definition for binary tree
     3  * struct TreeNode {
     4  *     int val;
     5  *     TreeNode *left;
     6  *     TreeNode *right;
     7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8  * };
     9  */
    10 class Solution {
    11 public:
    12     bool isValidBST(TreeNode *root) {
    13         int val = INT_MIN;
    14         return isValidBSTRe(root, val);
    15     }
    16     
    17     bool isValidBSTRe(TreeNode* root, int& val)
    18     {
    19         if(!root) return true;
    20         
    21         if(root->left && !isValidBSTRe(root->left, val))
    22             return false;
    23         if(root->val <= val) 
    24             return false;
    25         val = root->val;
    26         if(root->right && !isValidBSTRe(root->right, val))
    27             return false;
    28         return true;
    29     }
    30 };
  • 相关阅读:
    android开发 PopupWindow 设置充满屏幕
    android 设置半透明
    web farm 讨论引出
    xamarin studio And linq 查询方式分析
    MONO 使用重要提示
    一个MVC的在线编译工具
    MONO Jexus部署最佳体验
    Origami
    产品原型设计工具 Balsamiq Mockups(转)
    VSPM虚拟串口使用
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3649673.html
Copyright © 2011-2022 走看看