Redian新闻
>
recover binary search tree 常数空间
avatar
recover binary search tree 常数空间# JobHunting - 待字闺中
m*1
1
Two elements of a binary search tree (BST) are swapped by mistake.
Recover the tree without changing its structure.
如果中序遍历后存起来自然是好解决,可是不满足空间要求,如何在O(1)空间做到?
avatar
c*t
2
in order traverse不存,只存前一个node,比较current与前一个的值。
如果只有一次不满足 current.val >= previous.val, swap their values.
如果有两次不满足,记录第一次的 previous 和第二次的current, swap their values

【在 m*******1 的大作中提到】
: Two elements of a binary search tree (BST) are swapped by mistake.
: Recover the tree without changing its structure.
: 如果中序遍历后存起来自然是好解决,可是不满足空间要求,如何在O(1)空间做到?

avatar
e*e
3
Inorder traverse, keep the prev value and prev tree node,
Find first misplaced node by
if ( current.val < prev.val )
Node first = prev;
Find second by
if ( current.val < prev.val )
Node second = current;
After traversal, swap the values of first and second node.
Only need two pointers, prev and current node, and two variables, first and
second node. O(1) space.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。