1. 程式人生 > >LeetCode算法系列:98.Interleaving String

LeetCode算法系列:98.Interleaving String

題目描述:

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.

演算法實現:

直接上演算法,遞迴或者中序遍歷的方式,註釋寫的比較清楚

//想法,中序遍歷,如果為升序則true,否則判錯
//實際上嚴格意義上講,BST要求left <= root < right,即一個數如果和根節點相同,那麼只能在左側,所以嚴格意義上說是能用中序遍歷的,如兩個相同數字1組成的樹,一個1為1的左子樹,一個1為1的右子樹,這兩種情況中序遍歷相同,但是不都是true的
/**
 * 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) {
        return isValid(root,LONG_MIN,LONG_MAX);
    }
    bool isValid(TreeNode* root, long lbound, long ubound) {
        if(root == NULL) return true;
        //這個問題具體還是要求左<中<右來實現的,沒有嚴格按照BST的定義來實現;若想嚴格按照定義,只需要將下面一行的>=中的=去掉即可
        if(root -> val <= lbound || root -> val >= ubound)return false;
        return isValid(root -> left,lbound,root -> val) && isValid(root -> right, root -> val,ubound);
    }
};