[LeetCode] 897. Increasing Order Search Tree
Given the root of a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only one right child.
Example 1:
Input: root = [5,3,6,2,4,null,8,1,null,null,null,7,9]
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
Example 2:
Input: root = [5,1,7]
Output: [1,null,5,null,7]
Constraints:
The number of nodes in the given tree will be in the range [1, 100].
0 <= Node.val <= 1000
递增顺序搜索树。
给你一个树,请你 按中序遍历 重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
思路
这道题跟之前的114题很像,也是属于需要把树做扁平化处理的题目。既然题目都说了用中序遍历
,我这里给出两种做法,迭代和递归。时间空间复杂度均是 O(n)。看代码应该能明白思路,只是需要注意当处理节点的时候,需要找到新的 head 节点,以及把处理过的每个节点的左指针设置成 null
,新的树里面每个节点都只有右指针。
复杂度
时间O(n)
空间O(n)
代码
Java迭代实现
1 |
|
Java递归实现
1 |
|
相关题目
1 |
|
[LeetCode] 897. Increasing Order Search Tree
https://shurui91.github.io/posts/1227851573.html