[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迭代实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
// corner case
if (root == null) {
return null;
}
// normal case
TreeNode dummy = new TreeNode(0); // 虚拟头节点
TreeNode pre = dummy;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
cur.left = null;
pre.right = cur;
pre = cur;
cur = cur.right;
}
return dummy.right;
}
}
Java递归实现
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
TreeNode pre = null;
TreeNode head = null;
public TreeNode increasingBST(TreeNode root) {
if (root == null) {
return null;
}
increasingBST(root.left);
if (head == null) {
head = root;
}
if (pre != null) {
root.left = null;
pre.right = root;
}
pre = root;
increasingBST(root.right);
return head;
}
}
相关题目
114. Flatten Binary Tree to Linked List
430. Flatten a Multilevel Doubly Linked List
897. Increasing Order Search Tree