LeetCode --- Validate Binary Search Tree
生活随笔
收集整理的這篇文章主要介紹了
LeetCode --- Validate Binary Search Tree
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目鏈接
判斷一顆二叉樹是否是二叉搜索樹(二叉排序樹),也就是BST
如果該二叉樹是BST, 那么對其中序遍歷,所得序列一定是單調(diào)遞增的(不考慮有重復(fù)數(shù)值的情況)
附上代碼:
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 // "fa" holds the last value that has been visited 13 // "flag" is false when it(the given binary tree or its subtree) is an invalid BST 14 void InOrder(TreeNode *root, int& fa, bool& flag) { 15 if (root->left != NULL) { 16 InOrder(root->left, fa, flag); 17 } 18 if (root->val <= fa) 19 flag = false; 20 fa = root->val; 21 if (root->right != NULL) { 22 InOrder(root->right, fa, flag); 23 } 24 } 25 bool isValidBST(TreeNode *root) { 26 if (root == NULL || root->left==NULL&&root->right==NULL) return true; 27 // initialize "fa" as INT_MIN 28 // I assume that there are no tree node's val equals to INT_MIN 29 // and it does... (test case like this doesnt exist) 30 int fa = INT_MIN; 31 bool flag = true; 32 InOrder(root, fa, flag); 33 if (flag) 34 return true; 35 else 36 return false; 37 } 38 };?
轉(zhuǎn)載于:https://www.cnblogs.com/Stomach-ache/p/3770071.html
總結(jié)
以上是生活随笔為你收集整理的LeetCode --- Validate Binary Search Tree的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: RDIFramework.NET 中多表
- 下一篇: 解决ftp的pasv模式下iptable