173. 二叉搜索树迭代器/94. 二叉树的中序遍历/145. 二叉树的后序遍历/98. 验证二叉搜索树
生活随笔
收集整理的這篇文章主要介紹了
173. 二叉搜索树迭代器/94. 二叉树的中序遍历/145. 二叉树的后序遍历/98. 验证二叉搜索树
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2020-05-12
1.題目描述
二叉搜索樹迭代器2.題解
對于二叉搜索樹而言,進行中序遍歷就可以得到其有序序列,我們可以先對樹進行遍歷,將結果保存在 vector中,然后進行計算即可。3.代碼
173
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/ class BSTIterator { public:BSTIterator(TreeNode* root) {TreeNode* p=root;while (p||!mystack.empty()){while (p){mystack.push(p);p=p->left;}if (!mystack.empty()){myvector.push_back(mystack.top()->val);p=mystack.top();mystack.pop();p=p->right;}}index=0;}/** @return the next smallest number */int next() {return myvector[index++];}/** @return whether we have a next smallest number */bool hasNext() {if (index>=myvector.size()) return false;return true;}stack<TreeNode*> mystack;vector<int> myvector;int index; };/*** Your BSTIterator object will be instantiated and called as such:* BSTIterator* obj = new BSTIterator(root);* int param_1 = obj->next();* bool param_2 = obj->hasNext();*/94
/*** 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:vector<int> inorderTraversal(TreeNode* root) {vector<int> myvector;stack<TreeNode*> mystack;TreeNode* p=root;while (p||!mystack.empty()){while(p){mystack.push(p);p=p->left;}if (!mystack.empty()){p=mystack.top();mystack.pop();myvector.push_back(p->val);p=p->right;}}return myvector;} };145
/*** 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:vector<int> postorderTraversal(TreeNode* root) {vector<int> myvector;stack<TreeNode*> mystack;TreeNode* p=root;TreeNode* pre=p;while (p||!mystack.empty()){while (p){mystack.push(p);p=p->left;}TreeNode* top=mystack.top();if (!top->right||pre==top->right){myvector.push_back(top->val);mystack.pop();pre=top;}else{p=top->right;}}return myvector;} };98
一開始將pre設置成最小的int,沒想到測試樣例中竟然剛好出現了[-2147483648],只能使用long long /*** 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) {// 對其進行中序遍歷,看其是否是遞增的即可if (!root) return true; // 根節點為空stack<TreeNode*> mystack;TreeNode* p=root;long long pre=(long long)INT_MIN-1; // 保留其中序遍歷的上一個數,看是否滿足遞增的條件while (p||!mystack.empty()){while (p){mystack.push(p);p=p->left;}p=mystack.top();mystack.pop();if (p->val<=pre) return false;pre=p->val;p=p->right;}return true;} }; 新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的173. 二叉搜索树迭代器/94. 二叉树的中序遍历/145. 二叉树的后序遍历/98. 验证二叉搜索树的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JS基础_使用工厂方法创建对象(了解下就
- 下一篇: Qstring 与tr翻译过来的中文进行