一、题目
二、代码
/**
* 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
{
//取数,重新赋值
//<> () 前面表示大小,后面表示方法
List<Integer> re_list = new LinkedList<>();
int index = 0;
public void recursion_set(TreeNode pro)
{
if(pro.left!=null) recursion_set(pro.left);
pro.val=re_list.get(index++);
if(pro.right!=null) recursion_set(pro.right);
}
public void recursion(TreeNode pro)
{
if(pro.left!=null) recursion(pro.left);
re_list.add(pro.val);
if(pro.right!=null) recursion(pro.right);
}
public TreeNode convertBST(TreeNode root)
{
if(root==null) return null;
recursion(root);
int i ;
int length = re_list.size();
for(i=length-2;i>=0;i--)
{
re_list.set(i,re_list.get(i)+re_list.get(i+1));
}
// for(i=0; i<length; i++)
// {
// System.out.println(" "+re_list.get(i));
// }
recursion_set(root);
return root;
}
}
三、运行结果
四、附录
二刷
/**
* 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
{
//左中右遍历 中序遍历 就是从小到大
//先算总和 然后一个个减去赋值
int sum = 0 ;
int last_num = 0;
public void assign(TreeNode pro)
{
if(pro == null) return;
if(pro.left!=null) assign(pro.left);
int record = pro.val;
// int temp = sum-last_num;
// System.out.println(" last_num " +last_num);
// System.out.println(" pro " +pro.val);
// System.out.println(" assign " +temp);
sum = sum-last_num;
pro.val = sum;
last_num = record;
if(pro.right!=null) assign(pro.right);
}
public void track(TreeNode pro)
{
if(pro == null) return;
if(pro.left!=null) track(pro.left);
sum = sum+pro.val;
if(pro.right!=null) track(pro.right);
}
public TreeNode convertBST(TreeNode root)
{
int i;
track(root);
assign(root);
//System.out.println(" sum " +sum);
return root;
}
}