leetcode---recover-binary-search-tree---树
来源:互联网 发布:网络与internet连不上 编辑:程序博客网 时间:2024/06/05 22:40
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
Note:
A solution using O(n ) space is pretty straight forward. Could you devise a constant space solution?
confused what”{1,#,2,3}”means? > read more on how binary tree is serialized on OJ.
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}”.
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: TreeNode *p1 = NULL, *p2 = NULL, *pre = NULL; void dfs(TreeNode *root) { if(!root) return; dfs(root->left); if(pre && root->val < pre->val) { if(!p1) { p1 = pre; p2 = root; } else p2 = root; } pre = root; dfs(root->right); } void recoverTree(TreeNode *root) { dfs(root); if(p1 && p2) swap(p1->val, p2->val); }};
阅读全文
0 0
- leetcode---recover-binary-search-tree---树
- LeetCode: Recover Binary Search Tree
- LeetCode: Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- [leetcode] recover binary search tree
- LeetCode -- Recover Binary Search Tree
- [LeetCode]Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- LeetCode:Recover Binary Search Tree
- [Leetcode]Recover Binary Search Tree
- Leetcode: Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- [leetcode] Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree
- 【Leetcode】Recover Binary Search Tree
- Leetcode Recover Binary Search Tree
- jsp的用法
- HDU 3966 Aragorn's Story (树链剖分 区间更新,点查询)
- java对象的创建过程:类的初始化与实例化
- 正则表达式知识整理
- PTA 列车调度(25 分)
- leetcode---recover-binary-search-tree---树
- numpy.zeros()
- Leetcode||32. Longest Valid Parentheses
- Spring Boot集成Swagger2并替换默认的UI
- TS码流解析
- 阿里云发送短信验证码
- 让普通输入框具有Easyui输入框的样式,官方提供
- Spring Boot中使用Swagger2构建强大的RESTful API文档
- 对imageLoader进行配置的方法L