题目描述
Given a 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 1 right child.
方法思路
Approach1:
class Solution {
//Runtime: 27 ms, faster than 69.38%
//Memory Usage: 47.9 MB, less than 5.37%
//不知道为什么,只能List<Integer>,不能List<TreeNode>,否则就会超时,感觉怪怪的
private list = new LinkedList<>();
public TreeNode increasingBST(TreeNode root) {
if(root == null) return root;
inorder(root);
TreeNode ans = new TreeNode(0);
TreeNode cur = ans;
for(int x : list){
cur.right = new TreeNode(x);
cur = cur.right;
}
return ans.right;
}
public void inorder(TreeNode root){
if(root == null) return;
inorder(root.left);
list.add(root.val);
inorder(root.right);
}
}
Approach2:
We can perform the same in-order traversal as in Approach 1. During the traversal, we’ll construct the answer on the fly, reusing the nodes of the given tree by cutting their left child and adjoining them to the answer.
class Solution {
//Runtime: 24 ms, faster than 96.86%
//Memory Usage: 46.3 MB, less than 31.42%
TreeNode cur;
public TreeNode increasingBST(TreeNode root) {
TreeNode ans = new TreeNode(0);
cur = ans;
inorder(root);
return ans.right;
}
public void inorder(TreeNode node) {
if (node == null) return;
inorder(node.left);
node.left = null;
cur.right = node;
cur = node;
inorder(node.right);
}
}