1. 问题
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.
给定一个树,按中序遍历重新排列树,使树中最左边的结点现在是树的根,并且每个结点没有左子结点,只有一个右子结点。
2. 解题思路
按照中序遍历,并构建一棵新的树
3. 代码示例
/**
/**
* 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) {
ArrayList<Integer> list = new ArrayList<Integer>();
orderAndAddList(root, list);
TreeNode newnode = new TreeNode(0);
TreeNode cur = newnode;
for(int i = 0; i < list.size(); i++){
cur = cur.right = new TreeNode(list.get(i));
}
return newnode.right;
}
public void orderAndAddList(TreeNode root, ArrayList<Integer> list){
if(root == null) {
return;
}
orderAndAddList(root.left, list);
list.add(root.val);
orderAndAddList(root.right, list);
}
}