Recover Binary Search Tree
来源:互联网 发布:失踪的宝贝知乎 编辑:程序博客网 时间:2024/05/17 07:48
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: void Inorder(TreeNode *root, vector<TreeNode*> &nodes, vector<int> &vals) { if (!root) return; Inorder(root->left, nodes, vals); nodes.push_back(root); vals.push_back(root->val); Inorder(root->right, nodes, vals); } //void sort(vector<int> &vals) void recoverTree(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<TreeNode*> nodes; vector<int> vals; Inorder(root, nodes, vals); sort(vals.begin(), vals.end()); for (int i=0; i<nodes.size(); i++) { nodes[i]->val=vals[i]; } }};
Use inorder traverse because the numbers will be stored in an ascending order. The above solution need array to store all the values and consume O(n) space.
Below is the method needing O(1) space.
class Solution {public: TreeNode *n1, *n2, *pre; void inOrder(TreeNode *root) { if (!root) return; inOrder(root->left); if (pre && pre->val > root->val) { if (!n1) n1=pre; n2=root; } pre=root; inOrder(root->right); } void recoverTree(TreeNode *root) { n1=NULL; n2=NULL; pre=NULL; inOrder(root); int temp=n1->val; n1->val=n2->val; n2->val=temp; }};
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- Recover Binary Search Tree
- ios5和ios6横竖屏支持及ipad和iphone设备的判断
- Deformable Part Model的学习
- vs2012下 error4996
- hdu xxxx Peragrams
- fseek/ftell/rewind/fgetpos/fsetpos函数使用-linux
- Recover Binary Search Tree
- 《经济半小时》 20130906 指尖上的商机(五)数据时代
- 子程序重载
- Oracle中查询rownum和rowid的区别
- VS2008常见编译错误(总结篇)
- hdu-1018-Big Number
- 残疾山村老师30年学没近30大教生 月薪不到3百
- Java 理论与实践: 嗨,我的线程到哪里去了?
- handler.post(r)同一个线程的疑惑