24 把二叉搜索树转换为累加树
/**
* 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;//记录当前节点应该加的数值
public TreeNode convertBST(TreeNode root) {//用一个类属性sum帮助加数
//采取中序遍历,是右中左方式的
if(root == null) return null;
convertBST(root.right);
int val = root.val;
root.val += sum;//中节点处理逻辑,加上应该加的数值
sum += val;//下一个数应该加的数值
convertBST(root.left);
return root;
}
}
class Solution {
int pre = 0;//记录上一个节点的数值,也可以定义为TreeNode,不过要在加数值的时候判断一下是否为空
public TreeNode convertBST(TreeNode root) {//采用双指针
//采取中序遍历,是右中左方式的
if(root == null) return null;
convertBST(root.right);//其实可以另写一个返回值为void的函数,并不需要返回值,因为我直接更改原树的值
root.val += pre;//加上上一个节点的数值
pre = root.val;//更迭指针
convertBST(root.left);
return root;
}
}