標籤: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:
- 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.
confused what "{1,#,2,3}" means?
OJ‘s Binary Tree Serialization:
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 5
The above binary tree is serialized as
"{1,2,3,#,#,4,#,#,5}". 題意:給定一顆二叉樹,判斷該樹是否是二叉排序樹。二叉排序樹的規定:(1)如果存在左子樹,則左子樹的所有節點的值都要小於根節點的值。(2)如果存在右子樹,則右子樹的所有節點的值都要大於根節點的值。(3)如果一棵以root為根節點的樹是二叉排序樹,那麼其左子樹和右子樹也必須是二叉排序樹。 先給出我想到的解:在之前有寫到過用隊列建立一顆二叉排序樹,其過程類似於二叉樹的中序遍曆。因此,可以反過來看出二叉排序樹的中序遍曆的結果組成的序列應該是有序的。根據這種想法,可以得到如下代碼:
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/ 謝謝!