原题链接: https://leetcode.com/problems/increasing-order-search-tree/
1. 题目介绍
Given 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 1 right child.
给出一个二叉搜索树,使用中序遍历的方法,对其进行重新排列。使得原树的最左的节点,变成新树的根节点,新树中,每一个节点只有右节点,没有左节点。
Note:
The number of nodes in the given tree will be between 1 and 100.
Each node will have a unique integer value from 0 to 1000.
节点的数量范围是[1 , 100]
每个节点的val值范围是[0 , 1000]
2. 解题思路
方法1 中序遍历+保存到List中
可以先中序遍历整个树,将结果保存在一个List中,之后再遍历这个List,将所有的节点值都存入一个新树中,返回新树。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode increasingBST(TreeNode root) {
List<Integer> k = new ArrayList<>();
buildTree( root, k);
TreeNode pre = new TreeNode(0);
TreeNode temp = pre;
for(int i : k){
temp.right = new TreeNode(i);
temp = temp.right;
}
return pre.right;
}
public void buildTree(TreeNode root, List<Integer> k){
if(root == null){
return;
}
buildTree(root.left , k);
k.add(root.val);
buildTree(root.right , k);
}
}
方法2 中序遍历+直接改变原来的树
仍然使用中序遍历的顺序,对所有的节点进行遍历。不过不需要像方法1一样新建一个List存放节点val值,而是直接修改原来的树,当遍历完一个节点的左子树后,就削去它的左子树,直接把这个节点作为一个新的节点放入树中。
实现代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode pre = new TreeNode(0);
TreeNode temp = pre;
public TreeNode increasingBST(TreeNode root) {
buildTree( root);
return pre.right;
}
public void buildTree(TreeNode root){
if(root == null){
return;
}
buildTree(root.left);
root.left = null;
temp.right = root;
temp = temp.right;
buildTree(root.right);
}
}
3. 参考资料
https://leetcode.com/problems/increasing-order-search-tree/solution/