Try   HackMD

【LeetCode】 98. Validate Binary Search Tree

Description

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.

給予一個二元樹,判斷它是否為合法的二元搜索樹(BST)。

一個BST的定義為以下:

  • 左邊的子樹只會包含比你小的key的節點。
  • 右邊的子樹只會包含比你大的key的節點。
  • 左子樹和右子樹也都是二元搜索樹。

Example:

Example 1:

    2
   / \
  1   3

Input: [2,1,3]
Output: true


Example 2:

    5
   / \
  1   4
     / \
    3   6

Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.

Solution

  • 單純使用遞迴去跑所有節點即可,讓自己去和所有子樹去比大小,如果到NULL(空節點)為止都沒有錯誤就回傳true

Code

/** * 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 large(TreeNode* root, TreeNode* n) { if(!n) return true; if(root->val <= n->val) return false; return large(root, n->left) && large(root, n->right); } bool small(TreeNode* root, TreeNode* n) { if(!n) return true; if(root->val >= n->val) return false; return small(root, n->left) && small(root, n->right); } bool isValidBST(TreeNode* root) { if(!root) return true; if((large(root, root->left) && small(root, root->right)) == false) return false; return isValidBST(root->right) && isValidBST(root->left); } };
tags: LeetCode C++