Recover Binary Search Tree
Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure.
(复原二叉排序树)
Follow Up: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?
Example:
1. 中序遍历 & 树->数组
中序遍历二叉树,保存所有的节点到数组;然后遍历数组查找不符合要求的节点指针,空间复杂度为 O(n)。具体实现方法如下:
1 | # Definition for a binary tree node. |
2. 中序遍历
题中的 Follow Up 提及最好是空间复杂度为 O(1),因此在中序遍历的过程中需要同时找出不符合要求的节点指针。具体实现方法如下:
1 | # Definition for a binary tree node. |