标签:des style blog http color strong io for
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
confused what "{1,#,2,3}"
means?
The serialization of a binary tree follows a level order traversal, where ‘#‘ signifies a path terminator where no node exists below.
Here‘s an example:
1 / 2 3 / 4 5The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}"
.class Solution { public: bool isValidBST(TreeNode *root) { if(!root ||(!root->left && !root->right)) return true; vector<int> vi; vi.clear(); // 用非递归的方式对树进行中序遍历,将结果存放到vi数组中 stack<TreeNode* > s; TreeNode *tmp=root; while(!s.empty() || tmp){ if(tmp){ s.push(tmp); tmp = tmp->left; }else{ tmp = s.top(); s.pop(); vi.push_back(tmp->val); tmp = tmp->right; } } //对中序遍历的结果进行判断,注意不能有重复的数字 for(int i=1;i<vi.size();i++){ if(vi[i]<=vi[i-1]) return false; } return true; } };
转载请注明出处: http://www.cnblogs.com/double-win/ 谢谢!
[LeetCode 题解]: Validate Binary Search Tree,布布扣,bubuko.com
[LeetCode 题解]: Validate Binary Search Tree
标签:des style blog http color strong io for
原文地址:http://www.cnblogs.com/double-win/p/3880616.html